D
D
dikium2020-07-24 15:18:00
CORS
dikium, 2020-07-24 15:18:00

Why does sending application/json via axios cause a CORS error?

I'm trying to send a post request via axios to the server like this:

axios
        .post('/authors', {...this.loginFields, ...this.registerFields})
        .then(response => {
          if (response.data.result === 'success') {
            // success
          } else if (response.data.result === 'error') {
            // error
          }
        })
        .catch(error => console.error(error))


When doing this, I get the following error in the console:
5f1acea867a61012174765.png

With this request:
5f1ad078d7c63379855939.png

However, it is worth changing the sent data to a string, and I do not get this error. Those. this code is ok:
axios
        .post('/authors', JSON.stringify({...this.loginFields, ...this.registerFields}))
        .then(response => {
          if (response.data.result === 'success') {
            // success
          } else if (response.data.result === 'error') {
            // error
          }
        })
        .catch(error => console.error(error))


With this request:
5f1ad09202f8b759020957.png

At the same time, nginx is configured to send the cors header like this:
location / {
  add_header Access-Control-Allow-Origin *;
  try_files $uri $uri/ /index.php?$args;
}


What could be the issue here?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Anton Anton, 2020-07-24
@dikium

https://developer.mozilla.org/en/docs/Web/HTTP/CORS

Valid values ​​for the Content-Type header are:
application/x-www-form-urlencoded
multipart/form-data
text/plain

It's all about the setup.

K
Kirill Sharonov, 2020-07-24
@k_sharonov

Do you have a frontend and a backend on different "local domains"? Set up CORS and headers on the server.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question