I'm getting the next exeption when I call GET controller in production, in local works fine:
Resolved [org.springframework.web.bind.MissingRequestHeaderException: Required request header 'user_id' for method parameter type String is not present]
If I try using postman I got 400 Bad Request, in local works fine.
Here is my controler
#GetMapping(path ="/get")
public ResponseEntity <UserDto> getUserInformationById(#RequestHeader("user_id") final String id){
UserDto userDto = userInformationService.getUserInformationById(id);
if (userDto==null)
return ResponseEntity.notFound().build();
return ResponseEntity.ok(userDto);
}
Why is failing on production but not in local? another similar endpoints of the same class work fine, what am I missing?
I solved the issue by removing the underscore from the headers, I used userId
instead, and it worked.
Here you can read more about it
Related
In Spring Boot, I am configuring the server and everything is working, except of my RestController. I dont know why:
(SO doesnt allow to include pictures yet, so here is a link)
Thats the little Controller class. Notice, that the method name in my Intellij IDEA
is grey - it is not used.
package com.example.intermediate.controller;
import org.springframework.web.bind.annotation.*;
#RestController
public class GrakaController {
#GetMapping(value = "/graka", produces = "text/plain")
#ResponseBody
public String getSimpleString() {
return "IT WORKED!";
}
}
In Postman I try to get the String by using http://localhost:8080/graka: I am getting a 200 return code, but with empty response body, no matter which response body format I choose in Postman. But I should get "IT WORKED!" back I think.
I have been struggling for some hours with that. Who got any ideas? Thanks for every tip!
try this
#GetMapping("/graka")
public String getSimpleString(){
return "IT WORKED!";
}
With Spring 4, if your Controller is annotated with #RestController, you don't need the #ResponseBody annotation.
Use ResponseEntity.
#GetMapping("/graka")
public ResponseEntity<String> getSimpleString() {
LOG.info("REST request get string value");
return new ResponseEntity<>("{\"status\" : \"IT WORKED!\"}", HttpStatus.OK);
}
I have an assignment to write simple GET request.
The format that is going to be typed in URL is like this:
http://localhost:8080/api/tasks/20-08-2020
Server should return TODOs for that date. I did managed to write a finder method. But not sure how to write an endpoint. This is what I have so far:
#GetMapping(value = "/{date}", consumes="application/json")
public ResponseEntity<List<Task>> getTasksByDateUsingURL(#PathVariable("date") #DateTimeFormat(pattern="dd-MM-yyyy") #Valid LocalDate dueDate){
List<Task> tasks = taskService.getAllTasksByDate(dueDate);
return new ResponseEntity<List<Task>>(tasks,HttpStatus.OK);
}
This is inside RestController class:
#RestController
#RequestMapping(value="/api/tasks")
public class TaskController {...}
I cannot hit this GET endpoint...
Workaround for your problem is to get the string as parameter and parse it manually
#GetMapping(value = "/{date}", consumes="application/json")
public ResponseEntity<List<Task>> getTasksByDateUsingURL(
#PathVariable("date")
String date
){
LocalDate dueDate = parse(date);
List<Task> tasks = taskService.getAllTasksByDate(dueDate);
return new ResponseEntity<List<Task>>(tasks,HttpStatus.OK);
}
private LocalDate parse(String stringDate) {
// TODO
}
As author said in comments:
When try to call the endpoint from browser, the mapping is not executed.
Seems like that the browser is sending request with wrong Content-Type header. Your mapping is explicitly requires only application/json value.
When try to call the endpoint from Postman, the application returns 400 status.
I could not see the body of response, but I guess the problem is #Valid annotation on the parameter. How should Spring validate the LocalDate?
So the solution is to remove consumes="application/json" from mapping or send corresponding Content-Type value
and remove #Valid annotation from parameter.
I have an endpoint in the com.project.users package that will fetch the information of the logged in user:
#RestController
#RequestMapping(path = "/api")
public class UserController {
#Autowired
private UserRepository repository;
#GetMapping("me")
public User me() {
Optional<User> ouser = repository.findById(1);
return ouser.get();
}
}
I have another controller within com.project.beneficiary and I am trying to access a method through a POST request but instead, I receive a 404 error message:
Request URL:http://localhost:8080/api/beneficiaries
Request method:POST
Remote address:127.0.0.1:8080
Status code:
404
Version:HTTP/1.1
Referrer Policy:no-referrer-when-downgrade
{"timestamp":"2019-04-16T01:46:37.395+0000","status":404,"error":"Not Found","message":"No message available","path":"/api/beneficiaries"}
#RestController
#RequestMapping(path = "/api/beneficiaries")
public class BeneficiaryController {
#Autowired
private BeneficiaryRepository repository;
#PostMapping("/")
public Beneficiary addBeneficiary(#Valid #RequestBody Beneficiary beneficiary) {
return repository.save(beneficiary);
}
}
I've dealt with CORS, and I think it worked because I see no message about it anywhere. All these packages are on the same level as the application's starting point, but it is weird why one is seen and the other is not. Something to do with the POST request?
I found something about setting up the context within application.properties, but whatever I put there will cause the 404 error even from Insomnia software. I tried adding the /beneficiaries, /api/beneficiares, and just /api, but I don't think it is anything to do with it. No error messages in the console are visible.
It's a typo :). I ran into a similar problem some time back. Took me hours to resolve. Just remove ("/") from your #PostMapping.
I've made a simple static website, with some CSS & JS:
If I run this with SpringBoot, everything works pretty well, even JS works.
Now, I want to add a simple POST endpoint:
#RestController
public class Generator {
#RequestMapping(name = "/generator", method = RequestMethod.POST)
public String payload(final GeneratorPayload payload) {
System.out.println("This is your payload: " + payload.getFirstName());
return "testresp";
}
}
Which throws
org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'GET' not supported when accessing the main page (I'm not even calling that endpoint), displaying an error.
If I delete the inner mapping ("/generator"), everything works fine.
It's like he was overriding the default method and applies it to the index?
What's going on here?
There was an error here:
#RequestMapping(name = "/generator", method = RequestMethod.POST)
I've specified name, instead of value and the mapping was being attached to "/".
The correct version:
#RequestMapping(value = "/generator", method = RequestMethod.POST)
I am having trouble uploading files via AJAX from my web-client to my Server. I am using the following jQuery library in the client-side to do the file upload: https://github.com/hayageek/jquery-upload-file
In the server-side, I'm using Spring Framework and I have followed the following Spring Tutorial to build my Service: https://spring.io/guides/gs/uploading-files/
At first, my server method looked like this (file was defined as #RequestParam):
#RequestMapping(value="/upload", method=RequestMethod.POST)
public #ResponseBody String handleFileUpload(#RequestParam("file") MultipartFile file){
//functionality here
}
but every time I submitted the Upload form I got a Bad Request message from the Server, and my handleFileUpload() method was never called.
After that, I realized the file was not being sent as a Request Parameter so I defined file as #RequestBody, and now my method looks like this:
#RequestMapping(value="/upload", method=RequestMethod.POST)
public #ResponseBody String handleFileUpload(#RequestBody("file") MultipartFile file){
//functionality here
}
Now handleFileUpload() is called every time the Upload form is submitted, but I am getting a NullPointerException every time I want to manipulate file.
I want to avoid submitting the form by default, I just want to do it through AJAX straight to the Server. Does anybody know what could be happening here?
you may try changing the signature of the method to
#RequestMapping(value="/upload", method=RequestMethod.POST)
public #ResponseBody String handleFileUpload(MultipartHttpServletRequest request){
Iterator<String> iterator = request.getFileNames();
while (iterator.hasNext()) {
String fileName = iterator.next();
MultipartFile multipartFile = request.getFile(fileName);
byte[] file = multipartFile.getBytes();
...
}
...
}
this works with jQuery File Upload in our webapp. If for some reason this does
not work for you, you may try to isolate the problem, by inspecting the HTTP
request issued by the jQuery File Upload (for example, with Fiddler), and debugging the response starting from Spring
DispatcherServlet.