我正在尝试使用版本为2.0.5.RELEASE的Spring Boot构建RESTful API。这是我的控制器:
// Just for test
@RestController
public class LoginController {
@RequestMapping(value = "/user/login",method = RequestMethod.POST,produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<?> login(@RequestParam(name = "username") String username,
@RequestParam(name = "password") String password) {
ResponseEntity<RESTResponse> response = null;
if(username.equals("123") && password.equals("123")){
// success
response = new ResponseEntity<>(RESTResponse.generateResponse(
null, "successful", "Log in successfully."), HttpStatus.OK);
} else {
// failed
response = new ResponseEntity<>(RESTResponse.generateResponse(
null, "failed", "Your username or password is incorrect."), HttpStatus.OK);
}
return response;
}
}
这是Spring MVC配置类:
@Configuration
public class MyMvcConfig implements WebMvcConfigurer{
/**
* CORS configuration
*/
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins(ALL)
.allowedMethods(ALL)
.allowedHeaders(ALL)
.allowCredentials(true);
}
}
该控制器应该响应JSON数据。我用邮差测试了控制器。控制器可以接收请求参数并正常工作,但邮递员得到了一个奇怪的响应:
{
"timestamp": "2018-09-16T05:55:14.860+0000",
"status": 406,
"error": "Not Acceptable",
"message": "Could not find acceptable representation",
"path": "/api/user/login"
}
有人可以帮忙吗?
答案 0 :(得分:0)
确保在邮递员标题中使用Accept: application/json
。
如果完成上述操作,请尝试在方法签名中将consumes= MediaType.APPLICATION_JSON_VALUE
与Produces一起添加。
答案 1 :(得分:0)
您可以实现过滤器界面
并设置标题并接受所有方法
@Component
public class CORSFilter implements Filter{
static Logger logger = LoggerFactory.getLogger(CORSFilter.class);
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest request, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT");
chain.doFilter(request, response);
logger.info(request.getRemoteAddr());
}
public void destroy() {}
}
答案 2 :(得分:0)
确保您拥有这些罐子,并在邮递员标题中使用标题Accept: application/json
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.4.1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.4.1.1</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-core-asl</artifactId>
<version>1.9.13</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</version>
</dependency>