Express(backend)とReact(frontend)を用いてweb applicationの開発を行っているとCORS Errosに遭遇した.状況としては,ExpressとReactで開発を行う際には,Reactを3001番ポート,Expressを3000番ポートに開いており,ReactからExpressにユーザー認証を行うためにaxiosのGET methodでリクエストを行う必要があった.
何も設定しないと,CORS policyに違反する状況となってしまった.
そこで回避するために,Expressのindex.ts(.js)に以下の行を加えた.
app.use(function(req, res, next) { res.header("Access-Control-Allow-Origin", "*") // update to match the domain you will make the request from res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept") res.setHeader("Access-Control-Allow-Methods", "POST, GET") res.setHeader("Access-Control-Max-Age", "3600") res.setHeader("Access-Control-Allow-Headers", "Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, x-access-token, x-user-id,Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers") next() })
もし,headerの部分に自分で設定した変数名を渡す場合は,res.setHeader(“Access-Control-Allow-Headers” ) の第2引数の部分に,その変数名を追加する必要がある.
僕の場合は,”x-access-token”, “x-user-id” を追加した.
参考文献
- Access-Control-Allow-Origin: Dealing with CORS Errors in React and Express
https://daveceddia.com/access-control-allow-origin-cors-errors-in-react-express/ - Axios having CORS issue
https://stackoverflow.com/questions/50949594/axios-having-cors-issue - Cross-Origin Resource Sharing (CORS)
https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS - Axios POST works but axios.create POST generate 400 Bad Request Error
https://stackoverflow.com/questions/59498971/axios-post-works-but-axios-create-post-generate-400-bad-request-error - Request header field Access-Control-Allow-Headers is not allowed by Access-Control-Allow-Headers
https://stackoverflow.com/questions/25727306/request-header-field-access-control-allow-headers-is-not-allowed-by-access-contr - Request header field x-access-token is not allowed by Access-Control-Allow-Headers
https://stackoverflow.com/questions/39345378/request-header-field-x-access-token-is-not-allowed-by-access-control-allow-heade/40596564
コメント