-2

I am trying to send https request from ReactJs to NodeJs using axios. but i always getting the error Access to XMLHttpRequest at 'https://sadsadsadsa.com/get-data' from origin 'https://sdadsads432a.com' has been blocked by CORS policy: Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response.

My NodeJs :

const express = require('express')
const app = express()
const port = 3000
let bodyParser = require('body-parser')
let cors = require('cors')

app.options('*', cors({ allowedHeaders: true, optionsSuccessStatus: 200, preflightContinue: true, origin: '*' }))

app.post('/get-data', (req, res) => {
    res.setHeader("Access-Control-Allow-Origin", "*");
    res.setHeader("Access-Control-Allow-Headers", "*");
    res.setHeader("Access-Control-Allow-Methods", 'OPTIONS,POST,GET')
    res.setHeader("Content-Type", "application/json")

    if (req.body.access_key == '#3zF932988011ec3c1x8F@11ec3c1x8f') {
        res.json({ token: 'Token' })
    }
})

app.listen(port, () => {
    console.log(`Example app listening on port ${port}`)
})

ReactJs :

axios.post('https://sadsadsadsa.com/get-data',{ api, 'access_key': '#3zF932988011ec3c1x8F@11ec3c1x8f' },{}).then((res) => {
    mobileToken = res.data.token
    resolve('done')
})

How can i overcome this issue.

Adhil mhdk
  • 89
  • 2
  • 9
  • All those `Access-Control-Allow-*` headers are _response_ headers, not _request_ headers. They have no place in the request; drop them altogether. If you control the server, [configure it for CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS). If not, you're out of luck. – jub0bs May 01 '22 at 09:00
  • Does this answer your question? [CORS error even after setting Access-Control-Allow-Origin or other Access-Control-Allow-\* headers on client side](https://stackoverflow.com/questions/44232370/cors-error-even-after-setting-access-control-allow-origin-or-other-access-contro) – jub0bs May 01 '22 at 09:01

1 Answers1

-2

try using this

app.use(cors())
  • You should also [add a description to your code](https://meta.stackoverflow.com/q/392712/979052), as explaining what it does will help OP and others learn. – Alicia Sykes May 02 '22 at 15:05