如何在node.js中允许CORS?

问题描述 投票:0回答: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 选项。我仍然收到上述错误。

节点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 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;

我该如何解决这个问题?

javascript node.js reactjs axios
3个回答
2
投票

自从你使用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:在您的反应应用程序中”之前插入“http://”。

示例

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

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");
...
});

0
投票

除非您将原点作为数组传递,否则这将不起作用

app.use(
  cors({
    origin: ["*"],
    credentials: true,
  })
);

确保 origin 是一个数组

© www.soinside.com 2019 - 2024. All rights reserved.