-1

I have a web server, which has API.I used Postman to create POST and Get requests, and all worked fine. Now I've started to write a front-end app, and I cannot make a post request from browser. When I run index.html from my computer, I get this Error: "Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://localhost:3000/python. Reason: CORS header 'Access-Control-Allow-Origin' missing". Here is my code:

async function createRes(){
  try { const connect = await fetch ('http://127.0.0.1:3000/python',
    {method:"POST",
    body:JSON.stringify({date:"01/02/2019"}),
    headers:{"Content-Type":"application/json",
    "Access-Control-Allow-Origin":"*"
    }, 
    credentials:"include"})

    const data = await connect.json();
  } catch(error){
      console.log(error.message)} 
}
Abdul Hoque Nuri
  • 1,105
  • 1
  • 9
  • 18
Yuri Molodyko
  • 590
  • 6
  • 20
  • 2
    Hi Yuri, what are you using for your back-end? As others have suggested your back-end needs to have CORS enabled. It seems your using Python? So maybe something like this: https://flask-cors.readthedocs.io/en/latest/ – Inch High Dec 09 '19 at 10:46
  • I use express (node.js) – Yuri Molodyko Dec 09 '19 at 10:48
  • 1
    Hello @Yuri Molodyko, This happens very often locally. I see you're on: https://localhost:3000/python If you can do a test on an external server, it can work. Can you do the test? Have a good day and be brave! – Mickael Lherminez Dec 09 '19 at 10:59

4 Answers4

2

For Express please try:

npm install cors

Then, in your index.js file:

const app = express()
app.use(cors())
Inch High
  • 835
  • 5
  • 17
1

You need to configure CORS on the web server hosting the API

jared
  • 473
  • 3
  • 16
1

The problem does not lie in your front-end app, but on the server-side (your API). You have to configure your server to allow CORS requests from your app. Adding 'Access-Control-Allow-Origin' header to the request will not change anything. More about CORS here. There's nothing else I can write to help you, since you didn't provide any information about your API.

Maciej B. Nowak
  • 1,180
  • 7
  • 19
1

You will need to enable CORS on the API you are running on localhost (http://localhost:3000/python).

Essentially moving the: Access-Control-Allow-Origin: * to your API rather than the client making the request.

Ryan McDonough
  • 9,732
  • 3
  • 55
  • 76