admin管理员组

文章数量:1327966

I have a React app (localhost:3000) and a Node app (localhost:3001) to run a simple system. The problem is I'm getting the error 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.

I have tried with app.use(cors()) and also with cors options as below. Still I'm getting the above error.

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 app.js

import React, { Component } from "react";
import axios from 'axios';

class App extends Component {

ponentDidMount(){ 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;

How can I solve this?

I have a React app (localhost:3000) and a Node app (localhost:3001) to run a simple system. The problem is I'm getting the error 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.

I have tried with app.use(cors()) and also with cors options as below. Still I'm getting the above error.

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 app.js

import React, { Component } from "react";
import axios from 'axios';

class App extends Component {

ponentDidMount(){ 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;

How can I solve this?

Share Improve this question edited Nov 22, 2021 at 4:21 David Johns asked Nov 22, 2021 at 4:04 David JohnsDavid Johns 1,7346 gold badges23 silver badges60 bronze badges 6
  • stackoverflow./questions/56644035/… – Andy Commented Nov 22, 2021 at 4:14
  • @Andy I added those headers and updated my question as well. But still it gives the CORS error – David Johns Commented Nov 22, 2021 at 4:22
  • @Amadan The Node server is running on 3001 port. And even with app.use(cors()) the same error es – David Johns Commented Nov 22, 2021 at 4:24
  • Are you building your app with create-react-app? – Andy Commented Nov 22, 2021 at 4:30
  • @Andy Yes, with create-react-app – David Johns Commented Nov 22, 2021 at 4:36
 |  Show 1 more ment

2 Answers 2

Reset to default 2

Since you use nodejs

installing cors

npm install cors

After that

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')
})

Then after applying "cors" middleware. You need to insert "http://" before "localhost: in your react app".

Example

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

You are using a different port to the one defined in corsOptions, try like below.

// app.js

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

Update:

Change all references to 3000 to be 3001, so that your CORS configuration matches the request you are trying to make.

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

本文标签: javascriptHow to allow CORS in nodejsStack Overflow