0
votes

I am getting following error while calling post API.

405 Method Not Allowed

From angular i am calling post API like following.

private createFormUrl = `api/form/add`

public createForm(form: Form): Observable<string> {
    return this.httpClient.post<any>(this.createFormUrl, form)
      .pipe(catchError(this.handleError));
}

API in JAVA

@RestController
@RequestMapping( value = "/api/form")
public class FormManagementController {

private FormManagementService formmanagementService;

@PostMapping(path = "/add",
            consumes = MediaType.APPLICATION_JSON,
            produces = MediaType.APPLICATION_JSON)
    public ResponseEntity<?> createForm(@RequestBody(required = false) Form form) {
        String respond = formmanagementService.createForm(form);
        return ResponseEntity.status(getProperHttpStatus(respond)).build();
    }

Error:

URL: http://localhost/api/form/add (Working in postman)

enter image description here

I checked but, GET is not written any where for this API.

I checked many posts on stackoverflow but, nothing work for me. Any help would be greatly appreciated.

4

4 Answers

0
votes

Try it in Postman collection to ensure its working

So you can isolate its a angular specific issue, You didn't share the request payload. If not workign in post man alos then make code changes.

Instead of @PostMapping try this @RequestMapping(value = "/add", method = RequestMethod.POST)

Full example Ref : Spring Boot 405 POST method not supported?

0
votes

You need to use MediaType.APPLICATION_JSON_VALUE to get the media type string value.

@PostMapping(path = "/add",
            consumes = MediaType.APPLICATION_JSON_VALUE,
            produces = MediaType.APPLICATION_JSON_VALUE) {
    ...
}
0
votes

You better try with 'application/json' rather than MediaType.APPLICATION_JSON Not to defame anything, again. But there seems to be much topics upon the net about what should be used as the JSON MIME type.

The spec lists clearly only one MIME media type for JSON and it is "application/json" (see https://www.rfc-editor.org/rfc/rfc4627, section "6. IANA Considerations".

Just give a shot with the MIME type as 'application/json' in both consumes and produces.

@Robert

0
votes

It is clear that the response headers do not indicate that POST is allowed. The allow methods header should return something like GET, POST, PUT, DELETE, OPTIONS, HEAD'. Please add an attribute to the controller like so: @CrossOrigin(origins = "*", methods= "*"). methods is the property which will set the response header that lists which methods are allowed. Only browsers enforce CORS. Postman, curl don't enforce CORS. So, errors such as these are not evident at first glance. Hope that helps.