Http failure during parsing (angular/java) - java

Hi guys im working on an angular project with a java (spring boot) backend and sql server for database,i have a method that uses "Get" but im getting the following error:
headers: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, lazyInit: ƒ}
status: 200
statusText: "OK"
url: "http://localhost:8080/admin/allcompanies/02ff0785-3739-4f8d-b77f-eff6b77954f8"
ok: false
name: "HttpErrorResponse"
message: "Http failure during parsing for http://localhost:8080/admin/allcompanies/02ff0785-3739-4f8d-b77f-eff6b77954f8"
error: {error: SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) at XMLHttpRequest.onL…, text: "[{"id":2,"name":"Comp2","password":"comp2","email"…lcompanies/02ff0785-3739-4f8d-b77f-eff6b77954f8"}"}
__proto__: HttpResponseBase
Ive tried adding {responseType: 'arraybuffer'})/text/blob but im getting a compliation error
error TS2322: Type '"arraybuffer"' is not assignable to type '"json"'.
code snippits:
relevant service:
#Injectable({
providedIn: 'root'
})
export class AdminService {
constructor(private client: HttpClient) { }
public getAllCompanies(): Observable<Company[]>{
return this.client.get<Company[]>("http://localhost:8080/admin/allcompanies/" + sessionStorage.token);
}
method component:
#Component({
selector: 'app-get-all-companies',
templateUrl: './get-all-companies.component.html',
styleUrls: ['./get-all-companies.component.css']
})
export class GetAllCompaniesComponent implements OnInit {
public companies : Company[]=new Array();
constructor(private client:AdminService) { }
ngOnInit() {
this.client.getAllCompanies().subscribe(companies => {
this.companies=companies;
});
}
}
my routing:
const routes: Routes = [
{path: "login", component: LoginComponent},
{path: "admin", component : AdminComponent},
{path:"home",component:HomeComponent},
{path:"addcomp",component:AddCompanyComponent},
{path:"updatecomp",component:UpdateCompanyComponent},
{path:"deletecomp",component:DeleteCompanyComponent},
{path:"allcompanies",component:GetAllCompaniesComponent},
{path:"company",component:GetOneCompanyComponent},
{path:"", redirectTo: "home", pathMatch: "full"}
];
#NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
and my backend controller:
#CrossOrigin(origins = "http://localhost:4200")
#RestController
#RequestMapping("admin")
public class AdminController {
#Autowired
Map<String, Session> sessionsMap;
#GetMapping("/allcompanies/{token}")
public ResponseEntity<Object> getAllCompanies(#PathVariable String token) {
Session session = sessionsMap.get(token);
if (session != null) {
// session.setLastAccessed(??);
AdminFacade facade = (AdminFacade) session.getFacade();
return ResponseEntity.ok(facade.getAllCompanies());
} else {
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Unauthorized login");
}
}

Related

Angular : Http failure response for http://localhost:8082/employee/all: 0 Unknown Error

I'm trying to fetch a list of employees from a Spring Boot back-end using Angular's HttpClient module, but I'm getting the error "Http failure response for http://localhost:8082/employee/all: 0 Unknown Error." in my Angular app.
Here's my app.component.ts file:
export class AppComponent implements OnInit {
public employees: Employee[] | undefined;
constructor(private employeeService: EmployeeService) {}
ngOnInit(): void {
this.getEmployees();
}
public getEmployees(): void {
this.employeeService.getEmployees().subscribe(
(response: Employee[]) => {
this.employees = response;
},
(error: HttpErrorResponse) => {
alert(error.message);
}
)
}
}
And here's my employee.service.ts file:
#Injectable({
providedIn: 'root',
})
export class EmployeeService {
private apiServerUrl = environment.apiBaseUrl;
constructor(private http: HttpClient) {}
public getEmployees(): Observable<Employee[]> {
return this.http.get<Employee[]>(`${this.apiServerUrl}/employee/all`);
}
public addEmployee(employee: Employee): Observable<Employee> {
return this.http.post<Employee>(
`${this.apiServerUrl}/employee/add`,
employee
);
}
public updateEmployee(employee: Employee): Observable<Employee> {
return this.http.put<Employee>(
`${this.apiServerUrl}/employee/update`,
employee
);
}
public deleteEmployee(employeeId: number): Observable<void> {
return this.http.delete<void>(
`${this.apiServerUrl}/employee/delete/${employeeId}`
);
}
}
And here is the terminal output from the back-end:
GET http://localhost:8082/employee/all
HTTP/1.1 200 Content-Type: application/json Transfer-Encoding:
chunked Date: Fri, 27 Jan 2023 16:00:06 GMT Keep-Alive: timeout=60
Connection: keep-alive
[ {
"id": 5,
"name": "Millard Gerhartz",
"email": "mgerhartz0#so-net.ne.jp",
"jobTitle": "Business Systems Development Analyst",
"phone": "487-530-7589",
"imageUrl": "https://img.freepik.com/free-photo/close-up-young-successful-man-smiling-camera-standing-casual-outfit-against-blue-background_1258-66609.jpg?w=2000",
"employeeCode": "4d6ca12b-94fc-4d64-8ea3-d4c3e2cfdfc3" }, {
"id": 6,
"name": "Terencio Stoate",
"email": "tstoate0#howstuffworks.com",
"jobTitle": "Budget/Accounting Analyst II",
"phone": "936-713-6713",
"imageUrl": "http://dummyimage.com/147x100.png/cc0000/ffffff",
"employeeCode": "a0154f0f-5e8e-4456-8cb6-93f693dbf462" } ]
Response code: 200; Time: 157ms; Content length: 610 bytes
It seems like employees list is always empty
I resolved my own issues in Spring Boot by adding a CorsFilter Bean
I was running into CORS issues when trying to connect my Angular front-end application to my Spring Boot back-end API. After some research, I resolved the issue by adding a CorsFilter Bean to my Spring Boot application.
Here is the code I added under the main method in my Spring Boot
application:
#Bean
public CorsFilter corsFilter() {
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.setAllowCredentials(true);
corsConfiguration.setAllowedOrigins(Arrays.asList("http://localhost:4200"));
corsConfiguration.setAllowedHeaders(Arrays.asList("Origin", "Access-Control-Allow-Origin", "Content-Type",
"Accept", "Authorization", "Origin, Accept", "X-Requested-With",
"Access-Control-Request-Method", "Access-Control-Request-Headers"));
corsConfiguration.setExposedHeaders(Arrays.asList("Origin", "Content-Type", "Accept", "Authorization",
"Access-Control-Allow-Origin", "Access-Control-Allow-Origin", "Access-Control-Allow-Credentials"));
corsConfiguration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS"));
UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();
urlBasedCorsConfigurationSource.registerCorsConfiguration("/**", corsConfiguration);
return new CorsFilter(urlBasedCorsConfigurationSource);
}
This code creates a CorsFilter bean and configures it with the necessary settings to allow requests from the specified origin ("http://localhost:4200" in this case) and sets various headers and methods that are allowed. This resolved the CORS issues and allowed my front-end application to communicate with the back-end API.

CSRF token mismatch Laravel Vue Axios

I have a problem typing a data request to api. I use laravel vue and axios to make a request. the following problem appears
exception: "Symfony\Component\HttpKernel\Exception\HttpException"
file: "/var/www/html/accurate/ibn_accurate_web_api/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.php"
line: 383
message: "CSRF token mismatch."
<script>
import axios from "axios"
// import pagination from 'laravel-vue-pagination'
export default {
name: "branch-list",
components: {
// pagination
},
data() {
return {
branch: {
type: Object,
default: null
}
}
},
mounted() {
this.list()
},
methods: {
async list(page = 1) {
await axios.post("http://ibn.tes/api/accurate/branch", {
code_database: 550724,
headers:{
"X-CSRF-TOKEN": window.Laravel.csrfToken
}
}).then(({ data }) => {
this.branch = data
console.log(data);
}).catch(({ response }) => {
console.error(response)
})
}
}
}
</script>

Angular / Spring Boot | error: SyntaxError: "JSON.parse: unexpected character at line 1 column 1 of the JSON data"

I am currently working on a tutorial to get to know Spring Boot and currently facing the following problem.
During my registration process (works correctly -> user ends up in the database) I get the status code 200/OK in the browser console, but also an error message regarding an incorrect syntax:
My backend code looks like this:
AuthController:
#RestController
#RequestMapping(value = "/api/auth")
#AllArgsConstructor
public class AuthController {
private final AuthService authService;
private final RefreshTokenService refreshTokenService;
#PostMapping(value = "/signup")
public ResponseEntity<String> signup(#RequestBody RegisterRequest registerRequest) {
/*
* RegisterRequest: Through this class we are transferring the user details like username, password and email as part of the RequestBody (DTO)
* */
authService.signUp(registerRequest);
return new ResponseEntity<>("Registration Successful", null, OK);
}
....
AuthService:
#Transactional
public void signUp(RegisterRequest registerRequest) {
User user = new User();
user.setUsername(registerRequest.getUsername());
user.setEmail(registerRequest.getEmail());
user.setPassword(passwordEncoder.encode(registerRequest.getPassword()));
user.setCreated(now());
user.setEnabled(false);
userRepository.save(user);
String token = generateVerificationToken(user);
String message = mailContentBuilder.build("Thank you for signing up to Spring Reddit, please click on the below url to activate your account : "
+ ACTIVATION_EMAIL + "/" + token);
mailService.sendMail(new NotificationEmail("Please Activate your account", user.get
Email(), message));
}
Used DTO:
public class RegisterRequest {
private String email;
private String username;
private String password;
}
My frontend code looks like:
SignUpComponent:
signUp() {
this.signUpRequestPayload.email = this.signUpForm.get('email').value;
this.signUpRequestPayload.password = this.signUpForm.get('password').value;
this.signUpRequestPayload.username = this.signUpForm.get('username').value;
this.authService.signUp(this.signUpRequestPayload).subscribe((data) => {
console.log('Sign up successful', data);
});
}
AuthService:
#Injectable({
providedIn: 'root'
})
export class AuthService {
private headers = new HttpHeaders({ 'Content-Type': 'application/json' });
constructor(private http: HttpClient) { }
signUp(signUpRequestPayload: SignUpRequestPayload): Observable<SignUpRequestPayload> {
const body = JSON.stringify(signUpRequestPayload);
return this.http.post<SignUpRequestPayload>('http://localhost:8080/api/auth/signup', body, { headers: this.headers });
}
}
Used interface:
export class SignUpRequestPayload {
email: string;
password: string;
username: string;
}
What am I doing wrong here?
I solved it like this:
signUp(signUpRequestPayload: SignUpRequestPayload): Observable<string> {
const body = signUpRequestPayload;
return this.http.post('http://localhost:8080/api/auth/signup', body, { responseType: 'text', headers: this.headers });
}
I had to remove from the post method and set the responseType to 'text'. I also had to remove the JSON.stringify() method and set the return type to Observable.
As your response("Registration Successful") is not valid JSON.
So please remove <SignUpRequestPayload> from below line
return this.http.post<SignUpRequestPayload>

Spring Rest Controller POST request doesn't work

I have a rest controller:
#RestController
#RequestMapping("/query")
public class QueryController {
#Autowired
private QueryService queryService;
#RequestMapping(value = "/select", method = RequestMethod.POST)
public #ResponseBody QueryResultDTO executeQuery(#RequestBody QueryDTO queryDTO) {
try {
QueryResultDTO queryResultDTO = queryService.executeQuery("select * from employees");
queryResultDTO.setSuccessful(true);
return queryResultDTO;
} catch (SQLException e) {
QueryResultDTO queryResultDTO = new QueryResultDTO();
queryResultDTO.setSuccessful(false);
queryResultDTO.setErrorMessage(e.getMessage());
return queryResultDTO;
}
}
}
and I try to send POST request from AngularJS controller:
app.controller("AppCtrl",function($scope,$http) {
var app = this;
$scope.execute= function () {
$http({
url: '../query/select',
method: "POST",
data: { 'message' : $scope.queryText }
})
.then(function(response) {
$scope.queryResult = response.data;
console.log($scope.queryResult);
console.log($scope.queryText)
},
function(response) {
console.log(response);
});
}
});
but It doesn't work. My executeQuery function in Spring Controller isn't even called.
But when I change RequestMethod to GET it works correctly.
#RestController
#RequestMapping("/query")
public class QueryController {
#Autowired
private QueryService queryService;
#RequestMapping(value = "/select", method = RequestMethod.GET)
public #ResponseBody QueryResultDTO executeQuery() {
try {
QueryResultDTO queryResultDTO = queryService.executeQuery("INSERT INTO employee VALUES (7,'dupa')");
queryResultDTO.setSuccessful(true);
return queryResultDTO;
} catch (SQLException e) {
QueryResultDTO queryResultDTO = new QueryResultDTO();
queryResultDTO.setSuccessful(false);
queryResultDTO.setErrorMessage(e.getMessage());
return queryResultDTO;
}
}
}
and in Angular controller:
app.controller("AppCtrl",function($scope,$http) {
var app = this;
$scope.execute= function () {
$http({
url: '../query/select',
method: "GET",
data: { 'message' : $scope.queryText }
})
.then(function(response) {
$scope.queryResult = response.data;
console.log($scope.queryResult);
console.log($scope.queryText)
},
function(response) {
console.log(response);
});
}
});
My main problem is that I'd like to send some data to my Spring controller and then send JSON in response to my Angular controller. Whith GET method response works perfectly, but when I use POST the controller method isn't even called.
Edit:
My QueryDTO class is simple:
public class QueryDTO {
private String message;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
And some logs with DEBUG level:
2016-06-06 09:28:23.697 DEBUG 7504 --- [nio-8090-exec-2] o.s.web.servlet.DispatcherServlet : Null ModelAndView returned to DispatcherServlet with name 'dispatcherServlet': assuming HandlerAdapter completed request handling
2016-06-06 09:28:23.698 DEBUG 7504 --- [nio-8090-exec-2] o.s.web.servlet.DispatcherServlet : Successfully completed request
Try adding the consumes=MediaType.APPLICATION_JSON_VALUE in your method.
#Transactional
#RequestMapping(value = "/userlogincheck", method = RequestMethod.POST, consumes=MediaType.APPLICATION_JSON_VALUE)
public #ResponseBody void userLoginCheck(#RequestBody UserImpl user, HttpServletRequest request, HttpServletResponse response) throws JSONException, IOException {
JSONObject json = new JSONObject();
try {
String email=user.getEmail();
Long userId=user.getId();
User loginData = accountService.userLoginCheck(email,userId);
if(loginData==null)
{
json.put("status", "FAILURE");
json.put("message", "user does not exist");
json.put("nextPage", "signIn");
}
else
{
json.put("status", "SUCCESS");
json.put("nextPage", updateState);
}
}
catch(Exception e) {
logger.info(e.getMessage());
}
response.setContentType("application/json;charset=UTF-8");
logger.info("response======" + json.toString());
PrintWriter out = response.getWriter();
out.write(json.toString());
}
I had the same issue and was able to fix it by adding CSRF token to my request (this is only an issue if you are using the WebSecurity). https://docs.spring.io/spring-security/site/docs/current/reference/html/csrf.html
This link describe the following steps:
1) Add the token to your header, with thymeleaf you do as follows (I think you can fetch the token from cookie as well):
<head>
<meta name="_csrf" th:content="${_csrf.token}"/>
.....
</head>
2) Change your request to include the CSRF token as follows (I am not familiar with angular but I guess you can set the header the same way as I did with Jquery):
var token = $("meta[name='_csrf']").attr("content");
$.ajax({
type: 'POST',
url: url,
data: JSON.stringify(newTodo),
headers: {
'X-CSRF-TOKEN': token
},
contentType: 'application/json',
dataType: 'json',
success: function(){
alert('callback ');
}
});

Angularjs Java Rest Service 415 Unsupported Media Type

Im working with java spring mvc and angular js.
I created a rest service:
#RestController
public class UserApiController {
#Autowired
private UserService userService;
#RequestMapping(value = "/users/createUser", method = RequestMethod.POST)
public #ResponseBody void addUser(#RequestBody UserRequestDTO newUser) {
userService.addUser(newUser);
}
And my angular controller like this:
var newUser = { surname : "orozco", name: "daniel", password: "pepe", email:"dani#dani.com" };
$http.post(getCompletePath("users/createUser"), JSON.stringify(newUser))
.success(function () {
alert("ok");
}).error(function () {
});
My UserRequestDTO
public class UserRequestDTO {
private String email;
private String password;
private String name;
private String surname;
+getters and setters
It return the following error: 415 (Unsupported Media Type).
If I send a string o no parameters, it works. So, the problem is in the parameters
I forget to include org.codehaus.jackson in pom.xml. It fixed the issue
I don't know AngularJS but try to add Content-Type in your AngularJS code. It should look something like this (according the spec https://docs.angularjs.org/api/ng/service/$http) :
var newUser = {
surname : "orozco",
name: "daniel",
password: "pepe",
email:"dani#dani.com" };
var req = {
method: 'POST',
url: getCompletePath("users/createUser"),
headers: {'Content-Type': 'application/json'},
data: newUser};
$http(req)
.success(function () {alert("ok");})
.error(function () {});
This could be because of the Content-Type header, try to include it explicitly
as follows,
var req = {
method: 'POST',
url: getCompletePath("users/createUser"),
headers: {
'Content-Type': 'application/json'
},
data: {surname : "orozco", name: "daniel", password: "pepe", email:"dani#dani.com" },
}
$http(req).success(function(){...}).error(function(){...});

Categories

Resources