【问题标题】:How to allow CORS in node.js?如何在 node.js 中允许 CORS?
【发布时间】:2021-12-31 18:13:21
【问题描述】:

我有一个 React 应用程序 (localhost:3000) 和一个 Node 应用程序 (localhost:3001) 来运行一个简单的系统。 问题是我遇到了错误 Access to XMLHttpRequest at 'localhost:3001/app' from origin 'http://localhost:3000' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, chrome-untrusted, https.

我已尝试使用 app.use(cors()) 以及如下的 cors 选项。我仍然收到上述错误。

节点 app.js

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

const corsOptions = {
    origin: 'http://localhost:3000/',
    credentials: true,
    optionSuccessStatus: 200
}

app.use(cors(corsOptions));

app.use(function (req, res, next) {
    res.header('Access-Control-Allow-Origin', "http://localhost:3000");
    res.header('Access-Control-Allow-Headers', true);
    res.header('Access-Control-Allow-Credentials', true);
    res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
    next();
});

app.use(express.json());

app.get('/app', (req, res) => {
    res.send({result: "hello"});
});

module.exports = app;

反应 app.js

import React, { Component } from "react";
import axios from 'axios';

class App extends Component {

componentDidMount(){ this.runInstance(); }

runInstance = () => {
        axios.get(`localhost:3001/app`)
        .then(res => {
            console.log("res", res);
        })
        .catch(err => {
            console.log("AXIOS ERROR:", err);
        })
    }

render() { return(<div></div>) }
}
export default App;

我该如何解决这个问题?

【问题讨论】:

  • @Andy 我添加了这些标题并更新了我的问题。但它仍然给出了 CORS 错误
  • @Amadan Node 服务器在 3001 端口上运行。即使app.use(cors()) 也会出现同样的错误
  • 您是否正在使用 create-react-app 构建您的应用程序?
  • @Andy 是的,使用 create-react-app

标签: javascript node.js reactjs axios


【解决方案1】:

既然你用的是nodejs

安装cors

npm install cors

之后

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

app.use(cors())

app.get('/products/:id', function (req, res, next) {
  res.json({msg: 'This is CORS-enabled for all origins!'})
})

app.listen(80, function () {
  console.log('CORS-enabled web server listening on port 80')
})

然后在应用“cors”中间件之后。您需要在“localhost: in your react app”之前插入“http://”。

示例

axios.get(`http://localhost:3001/api/app`)
        .then(res => {
            console.log("res", res);
        })
        .catch(err => {
            console.log("AXIOS ERROR:", err);
        })

【讨论】:

  • 我已经更新了我的答案@DavidJohns 让我知道它是否有效
【解决方案2】:

您使用的端口与corsOptions 中定义的端口不同,请尝试如下操作。

// app.js

...
runInstance = () => {
    axios.get(`http://localhost:3000/app`)
    .then(res => {
        console.log("res", res);
    })
    .catch(err => {
        console.log("AXIOS ERROR:", err);
    })
}
...

更新:

将所有对 3000 的引用更改为 3001,以便您的 CORS 配置与您尝试发出的请求相匹配。

const corsOptions = {
    origin: 'http://localhost:3001/',
    credentials: true,
    optionSuccessStatus: 200
}
...

app.use(function (req, res, next) {
    res.header('Access-Control-Allow-Origin', "http://localhost:3001");
...
});

【讨论】:

  • Node服务器运行在3001端口
  • 您描述的场景中的所有端口引用应该是相同的值,答案更新
猜你喜欢
  • 2017-07-16
  • 2018-03-02
  • 2019-12-30
  • 2021-11-17
  • 2021-10-23
  • 2023-03-30
  • 2014-08-13
  • 2017-12-22
  • 2017-07-28
相关资源
最近更新 更多