60
rated 0 times
[
62]
[
2]
/ answers: 1 / hits: 5286
/ 3 Years ago, mon, november 22, 2021, 12:00:00
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 {
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;
How can I solve this?
More From » node.js