Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/26.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js React.js localhost和Node Express服务器中的Cors问题_Node.js_Reactjs_Express_Cors_Digital Ocean - Fatal编程技术网

Node.js React.js localhost和Node 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

我一直在尝试将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 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));