How to fix “Response to preflight request doesn't pass access control check: It does not have HTTP ok status” error in react app with nodejs api

我是研究僧i 提交于 2019-12-25 01:13:28

问题


I have been trying to do an api call (nodejs with express running on localhost) from a react app running in the browser over a local dev server (web-pack dev server). Everything was working well until I tried to call the api. They are both running on separate ports.

I have tried adding the cors headers (Recommended by MDN) to both the post call (from the app in browser) and to the response from the Nodejs API but neither of these solved the issue.

Code for the api call (in browser):

const headers = {
  'Content-Type': 'application/json',
  'access-token': '',
  'Access-Control-Allow-Origin': '*',
}

export default async () => {
  try {
    const body = JSON.stringify({
      test: true,
    })
    const response = await fetch('http://localhost:1337/internal/provider/check_email_exist', {
      method: 'POST',
      headers,
      body,
    })
    console.log(response)
  } catch (e) {
    return e
  }
}

API Middleware (in nodejs):

// Verify All Requests
app.use(VerifyToken)

// Compress
app.use(compression())

// Helmet middlware
app.use(helmet())

// Body Parser
app.use(bodyParser.urlencoded({
  extended: false,
}))
app.use(bodyParser.json())

The expected result is to just give a 200 status code and respond with the data.

The actual output is:

OPTIONS http://localhost:1337/internal/provider/check_email_exist 404 (Not Found)
Access to fetch at 'http://localhost:1337/internal/provider/check_email_exist' from origin 'http://localhost:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

回答1:


Since you're using webpack-dev-server you can use the proxy option DevServerProxy.

Your configuration will look like this:

// webpack.config.js
devServer: {
    proxy: {
      '/internal': 'http://localhost:1337'
    }
  }

Since I can't see your express routes on your question I'm speculating about the proxy route if your API lives on /internal endpoint then you should modify your React code like this:

const response = await fetch('/internal/provider/check_email_exist', {
   method: 'POST',
   headers,
   body,
})

As you can see I ommited the https://localhost:1337 because the proxy option from webpack-dev-server will handle this and it will redirect to http://localhost:1337. Hope this will help you. Cheers, sigfried.

EDIT

As the comment on your question pointed out you should set the headers on your express server, not the client, for this task you can use the cors-middleware package.



来源:https://stackoverflow.com/questions/56083049/how-to-fix-response-to-preflight-request-doesnt-pass-access-control-check-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!