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?
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");
...
});
Related
I am developing the admin interface for my software and it was working fine in development (when I 'react start'). The problem is when I build and run it in production. React-admin won't load the data coming from the server, because of these 2 error in its requests.
OPTIONS http://localhost:3000/user?filter={}&range=[0,9]&sort=["id","ASC"] - CORS FAILED
GET http://localhost:3000/user?filter={}&range=[0,9]&sort=["id","ASC"] - NS_ERROR_DOM_BAD_URI
in development react-admin doesn't request 'options /user' neither I get these errors. I am using node express in the server side:
require('dotenv').config();
const express = require('express')
var cors = require('cors')
const app = express()
const port = process.env.SERVER_PORT;
const serverIp = process.env.SERVER_IP;
const { verifyUser } = require('./middleware/verification');
const { readUsers } = require('./db/dbManager');
app.use(cors())
app.get('/user', verifyAdmin, (req, res) => {
readUsers().then((response) => {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Expose-Headers', 'Content-Range');
res.setHeader('Content-Range', 'posts 0-24/319');
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify(response));
});
})
app.options('/user', verifyAdmin, (req, res) => {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Expose-Headers', 'Content-Range');
res.setHeader('Content-Range', 'posts 0-24/319');
res.setHeader('Content-Type', 'application/json');
res.end();
})
app.use(express.static('build'));
app.listen(port, () => {
console.log(`Example app listening at http://${serverIp}:${port}`)
});
How can I fix these errors I am having in production?
I have test with different solution but still error. I ran my code (backend) on Heroku, and I tested it with Postman.
Error is show like this
Error: getaddrinfo ENOTFOUND https
This is the app.js
const express = require('express')
const bodyParser = require('body-parser')
const mongoose = require('mongoose')
const paketRoutes = require('./routes/paket-routes')
const transaksiRoutes = require('./routes/transaksi-routes')
const laporanRoutes = require('./routes/laporan-routes')
const HttpError = require('./models/http-error')
const app = express()
const PORT = process.env.PORT || 5000
app.use(express.json())
app.use((req, res, next) => {
res.setHeader('Access-Control-Allow-Origin', '*')
res.setHeader('Access-Control-Allow-Headers', 'Origin, X-Request-With, Content-Type, Accept, Authorization')
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PATCH, DELETE')
next()
})
app.get('/', (req, res) => {
res.send('Halo')
})
app.use({
host:'ameera-laundry.herokuapp.com',
path:'/paket'
}, paketRoutes)
app.use('/transaksi',transaksiRoutes)
app.use('/laporan', laporanRoutes)
app.use((req, res, next) => {
const error = new HttpError('Could not find this route', 404)
throw error
})
app.use((error, req, res, next) => {
if(res.headerSent) {
return next(error)
}
res.status(error.code || 500)
res.json({message: error.message || 'an unknown error occured'})
})
mongoose
.connect('mongodb+srv://name:password#mern.tr8rx.mongodb.net/task?retryWrites=true&w=majority')
.then(() => {
app.listen(PORT)
})
.catch(err => {
console.log(err)
})
I test with 1 api using host and path, but still fail. Please help, I cant find another solution, Newbie here.
Thanks for the answer and solution, help me a lot.
So I'm working in React and keep getting different cors errors. On the internet I found that you can use express to solve the problem!
But now I keep getting the following error:
TypeError: Cannot read property 'prototype' of undefined
I tried 2 different solutions but it just doesn't work:
var express = require('express')
var cors = require('cors')
var app = express()
app.options('*', cors())
export const fetchData = (url, key) => {
let myHeaders = new Headers();
myHeaders.append("Authorization", 'Bearer ' + key);
let requestOptions = {
method: 'GET',
headers: myHeaders,
redirect: 'follow',
};
return fetch(url, requestOptions)
.then(response => response.json())
.then(result => result)
.catch(error => console.log('error', error))
}
The other one I tried is
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')
})
Can someone tell me what I'm doing wrong ?
Try to do both of this:
app.use(cors());
app.options('*', cors());
This resolved all my problems with CORS.
use this code to solve cors error
app.use(function(req, res, next) {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
res.setHeader('Access-Control-Allow-Headers', 'Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers,X-Access-Token,XKey,Authorization');
res.setHeader('Access-Control-Allow-Credentials', true);
res.setHeader('Cache-Control', 'no-cache, no-store, must-revalidate');
res.setHeader('Pragma', 'no-cache');
res.setHeader('Expires', 0);
next();
});
I want to fetch my NodeJS server, but I receive a Cross-Origin Request echec.
This is my index.js server :
const express = require('express')
if (process.env.NODE_ENV !== 'production') require('dotenv').config()
const routerIdeas = require('./routes/ideas')
const PORT = process.env.PORT || 5000
const app = express()
app.use(function (req, res, next) {
res.header("Access-Control-Allow-Origin", "*")
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept")
res.send(200)
next()
})
app.use('/api', routerIdeas)
app.listen(PORT, () => {
console.log(`Server is running on port : ${PORT}`)
})
I also tried with the npm CORS package but it's the same problem :
const express = require('express')
var cors = require('cors')
if (process.env.NODE_ENV !== 'production') require('dotenv').config()
const routerIdeas = require('./routes/ideas')
const PORT = process.env.PORT || 5000
const app = express()
app.use(cors())
app.use('/api', routerIdeas)
app.listen(PORT, () => {
console.log(`Server is running on port : ${PORT}`)
})
And this is my fetch by the React app :
useEffect(() => {
const getIdeas = async () => {
setIsLoading(true)
try {
const response = await fetch("https://localhost:3004/api/ideas")
const data = await response.json()
setIdeasArray(data)
setIsLoading(false)
} catch (err) {
console.error('getIdeas error: ', err, err.stack)
}
}
getIdeas()
}, [])
The browser's console always answer :
Blocking a Cross-Origin Request: the "Same Origin" policy does not allow viewing of the remote resource located at https://localhost:3004/api/ideas. Reason: CORS request failed.
Sorry, it was just a stupid error :
Wrong fetch URL => https://localhost:3004/api/ideas
Good fetch URL => http://localhost:3004/api/ideas
Why don't you use CORS node package (link)
I have used Postman to send Post requests and they are working fine but when I try to use axios it is giving me this error.
createAnimeList.js:27
Error: Network Error
at createError (createError.js:16)
at XMLHttpRequest.handleError (xhr.js:83)
xhr.js:178 POST http://localhost:4000/animes/add
net::ERR_CONNECTION_REFUSED
This is my backend code
router.post("/add", async (req, res) => {
console.log("Heeeere");
console.log(req.body.animeName);
var anime = new Animes({
animeName: req.body.animeName,
});
anime = await anime.save();
return res.send(anime);
});
Here is my React code where I am using Axios
onSubmit(event) {
event.preventDefault();
const anime = {
animeName: this.state.animeName,
};
console.log(anime);
axios
.post("http://localhost:4000/animes/add", anime)
.then((res) => console.log(res.data))
.catch((err) => console.log(err));
//window.location = "/anime";
}
Seems like a CORS issue
Install that on your node server:
https://www.npmjs.com/package/cors
Here is a simple example of node server with CORS enabled using this lib.
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')
})
you need to enable CORS( Cross-Origin-Resoruce-Sharing)
you can either use the cors package
https://www.npmjs.com/package/cors
or this code
place this controller before every controller in your application
app.use((req, res, next) => {
res.setHeader('Access-Control-Allow-Origin', '*'); // to enable calls from every domain
res.setHeader('Access-Control-Allow-Methods', 'OPTIONS, GET, POST, PUT, PATCH, DELETE'); // allowed actiosn
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
if (req.method === 'OPTIONS') {
return res.sendStatus(200); // to deal with chrome sending an extra options request
}
next(); // call next middlewer in line
});
It's a CORS issue:
You need to add the follow code in your backend:
const cors = require('cors');
const express = require('express');
const app = express();
app.use(cors({
credentials:true,
origin: ['http://localhost:PORT']
}));
Inside origin array you need to insert those urls who are in the white list.