Node.js React.js localhost和Node Express服务器中的Cors问题
我一直在尝试将Digital Ocean droplet上托管的API作为Node.js Express服务器调用。我遇到的问题是CORS。以下是我的客户端调用和错误Node.js React.js localhost和Node Express服务器中的Cors问题,node.js,reactjs,express,cors,digital-ocean,Node.js,Reactjs,Express,Cors,Digital Ocean,我一直在尝试将Digital Ocean droplet上托管的API作为Node.js Express服务器调用。我遇到的问题是CORS。以下是我的客户端调用和错误 export const postRequest = async (route, data, headers) => { let config = { headers: headers } let dataString = JSON.stringify(data) return
export const postRequest = async (route, data, headers) => {
let config = {
headers: headers
}
let dataString = JSON.stringify(data)
return instance.post(route, dataString, config)
.then((response) => {
return response.data
})
.catch((err) => {
console.log(err);
return {error: err}
});
}
服务器端只是一个简单的express服务器,代码中没有实现核心。我试过使用app.use(cors()),但运气不好,所以我现在就开始新的尝试。前端是react js和axios
我得到的错误是
Access to XMLHttpRequest at 'https://example.com/login' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
我需要在这里做什么?无论是客户端还是服务器端。无需担心!!!我在客户端犯了一个错误。要修复此错误,请转到服务器代码
npm install --save cors
加
重新启动服务器,就可以开始了。将此添加到服务器配置中
var corsOptions = {
origin: 'http://localhost:3000'
};
app.use(cors(corsOptions));
const cors = require('cors');
app.use(cors());
var corsOptions = {
origin: 'http://localhost:3000'
};
app.use(cors(corsOptions));