When sending a JSON package from a separate HTML file to Java Spring RestController using jQuery, java issues a warning:

Content type 'application / x-www-form-urlencoded; charset = UTF-8' not supported]

In this case, all MediaType listed.

Chrom gives 2 more errors:

POST http: // localhost / post 415

and

Access to XMLHttpRequest at ' http: // localhost / post ' from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header

Controller Code:

@RestController public class mainController { @RequestMapping(value = "/post", method = RequestMethod.POST, consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE, produces = {MediaType.APPLICATION_JSON_UTF8_VALUE}) public ResponseEntity<Object> postUser(@RequestBody User user){ System.out.println(user); return new ResponseEntity<>("Success", HttpStatus.OK); } } 

JQery code:

 $(document).ready(function() { $('#go').on('click', function() { var user = { "name" : "Tom", "age" : 23 }; $.ajax({ url: 'http://localhost/post', type: 'POST', dataType: 'json', data: user }) .done(function() { console.log("success"); }) .fail(function() { console.log("error"); }) .always(function() { console.log("complete"); }); }); }); 

A huge request to tell where is the error and how to solve this problem?

PS T.K. I don’t have enough experience to say how such applications are written, namely Backend first and then using Thymeleaf or Mustache Front templates, or is Frontend completely written separately like mine?

  • It’s unreasonable to write a front on a Timlyph, you need to make a request - Roman C

2 answers 2

 $.ajax({ type: 'POST', url: "http://localhost/post", contentType: 'application/json; charset=utf-8', data: JSON.stringify(user), dataType: 'json', async: true }); 
  • I configured Nginx to prevent the CORS blocking, inserted your code, the rest of the errors remained. - Vadim
  • Add to the request question with all the headers that your form submits. To understand why you had a CORS lock, you need to see the configuration of your application. What dependencies are connected and how and what is configured. - Vladimir Yarovoy 6:59 pm
  • There was a CORS lock because I didn’t pick up the HTTP server. - Vadim

Thank you all, figured out. It was necessary to raise the HTTP server so that there was no CORS blocking and tweak MediaType, namely, it left only produces = {MediaType.APPLICATION_JSON_UTF8_VALUE}.