Cross-Origin Request Blocked with React and Express

前端 未结 4 1193
长情又很酷
长情又很酷 2021-01-12 15:54

So I hit this error, when I was trying to send data to the back end using React. From what I learnt I need to allow the communication on the back-end and in the .htacc

相关标签:
4条回答
  • 2021-01-12 16:04

    if you add this header

    res.setHeader('Access-Control-Allow-Origin', '*');
    

    you're using credential mode (means you're sending some authentication cookie from your app) and as for CORS specification you cannot use the wildcard * in this mode.

    you should change your Access-Control-Allow-Origin header to match the specific host who generated the request

    you can change this line:

    res.header('Access-Control-Allow-Origin', '*');
    

    to

    res.header('Access-Control-Allow-Origin', 'the ip address');
    

    but to be more generic, something like this should work:

    res.setHeader('Access-Control-Allow-Origin', req.header('origin') 
    || req.header('x-forwarded-host') || req.header('referer') || req.header('host'));
    

    in addition you have even to allow OPTIONS requests from the browser otherwise you will get a preflight request error.

    res.setHeader('Access-Control-Allow-Methods', 'POST, OPTIONS');
    
    0 讨论(0)
  • 2021-01-12 16:05

    One reason might be you're using the route as localhost:8000 rather than http://localhost:8000.

    USE

    http://localhost:8000
    

    DON'T USE

    localhost:8000
    
    0 讨论(0)
  • 2021-01-12 16:09

    There's a node package called cors which makes it very easy.

    $npm install cors

    const cors = require('cors')
    
    app.use(cors())
    

    You don't need any config to allow all.

    See the Github repo for more info: https://github.com/expressjs/cors

    0 讨论(0)
  • 2021-01-12 16:21

    you have to allow OPTIONS method as well

    res.setHeader('Access-Control-Allow-Methods', 'POST, OPTIONS');
    

    the browser send it with any post request to other domain to check how it will communicate with this remote server.

    0 讨论(0)
提交回复
热议问题