K
K
Konstantin Bozhkov2017-10-15 23:47:25
JavaScript
Konstantin Bozhkov, 2017-10-15 23:47:25

Why doesn't cross-domain fetch work?

The issue is as follows, you need to send data to another domain. I have this implemented by 2 Node.js applications under different ports. On port 8080 (8081 - proxy) there is a UI server sharpened for isomorphic React ... On port 3000 there is an API server.

fetch('http://localhost:3000', {
  method: 'post',
  headers: {
    'Access-Control-Allow-Origin':'*',
     'Accept': 'application/json, text/plain, */*',
    'Content-Type': 'application/json'
  },
  mode: 'cors',
  body: JSON.stringify({a: 7, str: 'Some string: &=&'})
})
  .then(res=>res.json())
  .then(res => console.log(res));

The problem is that the "set" headers are not visible on the server. 59e3c5d996466258918039.png
If the request is sent to the same domain from which the page was loaded, then everything will be successful.
fetch('http://localhost:8080', {
  method: 'post',
  headers: {
    'Access-Control-Allow-Origin':'*',
     'Accept': 'application/json, text/plain, */*',
    'Content-Type': 'application/json'
  },
  mode: 'cors',
  body: JSON.stringify({a: 7, str: 'Some string: &=&'})
})
  .then(res=>res.json())
  .then(res => console.log(res));

As you can see in the photo, the headers are set correctly 59e3c7e520a9b993719457.png
. How to solve this problem? Thanks in advance!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Gontarev, 2017-10-16
@ybiks

Access-Control-Allow-Origin must be set not on the client, but on the server, on the server it is necessary to specify which domains can make a request, i.e. The response from the server must contain this header

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question