【发布时间】: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