简体   繁体   中英

I am trying to save data in database but facing error

Am creating a react app in which i am using api's for saving data to database but when i post request getting error

let responseData = await fetch('https://********************',
  {method: 'post',
    headers: {
    Accept: 'application/json',
    'Content-Type': 'application/json',
  },
body: JSON.stringify(data)});
responseData = responseData.json();```

**error**

Access to fetch at 'https://*********************' from origin 
'http://localhost:3000' has been blocked by CORS policy: Request 
header field access-control-allow-origin is not 
allowed by Access-Control-Allow-Headers in preflight response.
[![enter image description here][1]][1]


  [1]: https://i.stack.imgur.com/kMxKF.png

It looks like you need to enable CORS on your server.

I assume from your tags that you are using Express.

You can use the cors npm package:

npm install cors

Then in your app:

const express = require('express')
const cors = require('cors')
const app = express()

app.use(cors())

// The rest of your app

See the docs for more advanced usage: https://www.npmjs.com/package/cors

I hope this helps solve your problem.

are you trying to fetch directly from https://i.stack.imgur.com ? That won't work as you can see in the error. Browsers don't allow making requests to hosts that are not same origin unless explicitly allowed, which in your case is localhost . You would need to run your own server in order to fetch data from other sources. If you are already running a server on localhost you should be fine. But if you are running a server on some other host, you would explicitly need to allow localhost as an exception to CORS policy. Most server frameworks have option to set that. Just google for whatever server you are using :)

您可以为 chrome 安装Moesif Orign & CORS Changer并打开,它将为您工作

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM