如何在node.js中允许CORS?

3

我有一个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选项。 但我仍然遇到上述错误。

Node 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;

React 应用程序.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;

我该如何解决这个问题?


https://dev59.com/FTYCtIcB2Jgan1znT2zG - Andy
@Andy 我添加了这些头部,并且也更新了我的问题。但是仍然出现CORS错误。 - David Johns
@Amadan Node服务器正在3001端口上运行。即使使用了app.use(cors()),仍然出现相同的错误。 - David Johns
你是用 create-react-app 来构建你的应用程序吗? - Andy
@Andy 是的,使用 create-react-app。 - David Johns
我很惊讶你需要导航CORS。我从来没有遇到过这种情况。你可以尝试在你的package.json中添加代理信息 - Andy
2个回答

0

您正在使用与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");
...
});

1
Node服务器正在3001端口上运行。 - David Johns
描述中的所有端口引用应该是相同的值,回答已更新。 - Digital Fu

0

由于您使用的是Node.js

安装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”中间件之后,你需要在你的react应用程序中,在“localhost:”之前插入“http://”。 示例
axios.get(`http://localhost:3001/api/app`)
        .then(res => {
            console.log("res", res);
        })
        .catch(err => {
            console.log("AXIOS ERROR:", err);
        })

我已经更新了我的答案@DavidJohns,请告诉我它是否有效。 - Fiido93

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接