Проблема с CORS при получении пост-запроса ReactJS - PullRequest
0 голосов
/ 15 апреля 2020

Когда я отправляю этот запрос, я всегда получаю 403 код:

export const createNewItem = item => {
  return async dispatch => {
    let headers = new Headers();
    headers.append('Content-Type', 'application/json');
    headers.append('Accept', 'application/json');
    headers.append('Authorization', `Bearer ${localStorage.getItem('token')}`);

    await fetch(`http://myurl.herokuapp.com/items`, {
      method: 'POST',
      body: JSON.stringify(item),
      mode: 'no-cors',
      headers: headers
    })
      .then(res => res.json())
      .then(res => dispatch(createItemSuccess(res)))
      .catch(err => console.log(err));
  };
};

Когда я удаляю режим: 'no-cors', я получаю:

Доступ к выборке в ' http://myurl/items 'from origin' http://localhost: 3000 'заблокировано политикой CORS: Ответ на предпечатный запрос не проходит проверку контроля доступа: он не имеет статуса HTTP ok.

Кто-нибудь может мне помочь?

Код конечной точки в Kotlin + Spring api:

@Validated
@RestController
@CrossOrigin(origins = ["*"])
@RequestMapping("/items")
class ItemEndpoint(private val facade: ItemFacade,
                   private val validations: Validations) {

    @GetMapping(produces = [APPLICATION_JSON_VALUE])
    fun items(): MutableIterable<Item> = facade.getAllItems()

    @GetMapping("/{id}", produces = [APPLICATION_JSON_VALUE])
    fun byId(@PathVariable(name = "id") id: String): Item? = facade.getItemById(id)

    @PostMapping(produces = [APPLICATION_JSON_VALUE], consumes = [APPLICATION_JSON_VALUE])
    fun create(@RequestBody(required = true) itemRequest: ItemRequest): Item {
        validations.validate(itemRequest)

        return facade.create(itemRequest)
    }
}
...