I know that this question has been answered and some of them worked but for me it is not. I'm struggling to find a solution for this problem:
Access to XMLHttpRequest at 'http://lolcahost:9000/api/users' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
I already tried downloading a chrome extension but didn't help me and using app.use(cors()) also didn't help me.
This is my code in expressjs
/* Importing all necessary packages. */
const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
/* Default port */
const port = process.env.PORT || 9000;
/* Creating express object */
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use('/api', require('./routes/route'));
app.use(cors());
app.get('/', (request, response) => {
response.json({
HOME: "HELLO JSON"
})
});
app.listen(port, () => {
console.log(`Listening at port ${port}`)
});
and this is my code in vuejs where I'm trying to render the data.
getUsers() {
axios
.get("http://localhost:9000/api/users/")
.then(response => (this.results = response.data))
.catch(error => console.log(error));
}
You are using the cors middlware AFTER the /api routes. So, actually the cors middlware is not even being called. Put the cors above other middlwares.
const app = express();
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use('/api', require('./routes/route'));
Middlwares are called by the order they are initialised. Now, the /api is initialised first and is not a middleware(doesn't call the next() function) so after the routes any middleware is basically unreachable code.
Try this.
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "http://localhost:8080"); // update to match the domain you will make the request from
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
or
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");
next();
});
Related
Hy, I try to get some data from a nodeJs API. I use react for frontend. I make my node API, I test with Postman and it work fine. When I use axios for get my data from the server I get a cors Error.
This is my axios call from react:
async function getMagazin(){
return (await axios.get(URL)).data;
}
And this is my node Js API:
import express from 'express';
import bodyParser from 'body-parser';
import db from './dbConfig.js';
import Magazin from './entities/Magazin.js';
import cors from 'cors';
let app = express();
let router = express.Router();
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.use('/api', router);
app.use(cors());
app.use(function(req, res, next) {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
if ('OPTIONS' == req.method) {
res.sendStatus(200);
}
else {
next();
}});
async function getMagazin(){
return await Magazin.findAll();
}
router.route('/magazin').get(async (req, res) => {
res.json(await getMagazin());
})
let port = process.env.PORT || 8000;
app.listen(port);
console.log("API is running at " + port);
I try to add cors in my node API and hope the error is gone but not.
This is the error:
I try to make I debug, the api call go on the server and execute sql query, but when he return he give me that error. What I must add in my server side code for the API to work?
Switch the order so that cors is before api
app.use(cors());
app.use('/api', router);
When you use cors you have to indicate what domain or address can contact your api by adding it in the cors middleware like this:
app.use(cors({
origin: "http://localhost:3000"
}));
There are so many questions asked based on this issue but none solves my problem.
I am using cloud9 IDE for my development. I am trying to receive data from node server to angular project using a API. My node.js server has all the CORS header required. But I continue to receive the error.
Here is my server code:
var express = require('express'),
app = express(),
port = 8080,
bodyParser = require('body-parser');
const cors = require('cors');
app.use(cors());
const { expressCspHeader, INLINE, NONE, SELF } = require('express-csp-header');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(expressCspHeader({
policies: {
'default-src': [expressCspHeader.NONE],
'img-src': [expressCspHeader.SELF],
}
}));
app.use(cors());
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header('Access-Control-Allow-Methods', 'GET');
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
if ('OPTIONS' == req.method) {
res.sendStatus(200);
}
else {
next();
}});
var routes = require('./api/routes/doRoutes'); //importing route
routes(app);
app.use(function(req, res) {
res.status(404).send({url: req.originalUrl + ' not found'});
});
app.listen(port);
console.log('RESTful API server started on: ' + port);
Here is the error on firefox browser:
Is it the IDE thats causing the problem? Or am i missing out on something? Please help !
I think it's because you only have the get verb enabled in your backend
Change this:
res.header('Access-Control-Allow-Methods', 'GET');
for this:
res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, DELETE');
In my browser developer toolbar I get the following error message for a POST request:
Access to XMLHttpRequest at 'http://localhost:8000/api/tags/' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
However when I look into my server.js I do allow access:
app.prepare().then(() => {
const server = express();
server.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
Does anyone know why this is blocked now
Better to use the "cors" package as follows.
const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');
const cors = require('cors');
const app = express();
app.use(cors());
// some route controllers
const customRoute = require('./customRoute.controller');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
// Custom routes
app.use('/api/tags', customRoute);
app.use(express.static(path.join(__dirname, 'dist')));
// Catch all other routes & return index file
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'dist/index.html'));
});
module.exports = app;
I feel like I've tried everything, would appreciate some fresh eyes to look upon my problem. As the title suggests, I'm sending a http post request to my NodeJS server that is running express, and nodeJS returns the req.body to be undefined/empty.
NodeJS Express Code:
const express = require('express');
const path = require('path');
const app = express();
const PORT = process.env.PORT || 5000;
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");
next();
});
app.post('/addComment', (req, res) => {
console.log(req.body);
});
app.listen(PORT, () => console.log(`Listening on ${ PORT }`));
Javascript Browser Code:
let data = {name: 'aName'};
fetch('http://localhost:5000/addComment', {
method: 'post',
body: JSON.stringify(data)
});
You have to use body-parser middleware :
const bodyParser = require('body-parser')
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json());
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");
next();
});
app.post('/addComment', (req, res) => {
console.log(req.body);
});
app.listen(PORT, () => console.log(`Listening on ${ PORT }`));
see body-parser.
If you are using the latest express, you can actually use do
const express = require('express');
const path = require('path');
const app = express();
const PORT = process.env.PORT || 5000;
app.use(express.json())
app.use (express.urlencoded({extended: false}))
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");
next();
});
app.post('/addComment', (req, res) => {
console.log(req.body);
});
app.listen(PORT, () => console.log(`Listening on ${ PORT }`));
Express now bundle body-parser by default due to popular demand.
I would like to sue a middleware just for the /doc path so it can serve satic file and have a basic auth.
But when i try to get /doc i have a cannot get /doc error.
Does anyone have any idea ?
var app = express();
app.use(bodyParser.urlencoded({ extended: true })); // parse application/x-www-form-urlencoded
app.use(bodyParser.json()) ; // parse application/json
app.use(functio //app.use('/doc', express.static('./doc'));n(req, res, next) {
res.header("X-powered-by", "NodeJs");
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept,Authorization");
next();
});
app.use(function(req, res, next) {
console.log(' - ',req.originalUrl);
next();
});
var router = express.Router();
router.use(express.basicAuth('testUser', 'testPass'));
router.get('/doc', function(req, res, next) {
console.log("inside doc");
express.static('./doc');
next();
});
app.use('/conf',require('./v1/data_config'));
thanks and regard
2 Things:
You have to add your router to your express app and you should move the '/doc' route outside of your router as authentication could interfere with your app.
var router = express.Router();
router.use(express.basicAuth('testUser', 'testPass'));
router.get('/', express.static('doc'));
app.use('/doc',router);