axios autohorization headers / CORS error - node.js

I'm using react with axios to fetch some information. I'm sending JWT token to auth user and im geting response in console browser
"Access to XMLHttpRequest at 'https://beer-tonight.herokuapp.com/beer/getBeerStatus' from origin 'http://localhost:3000' has been blocked by CORS policy: Request header field authorization is not allowed by Access-Control-Allow-Headers in preflight response."
This is my code:
componentWillMount(){
let token = localStorage.getItem('token');
axios.get('https://beer-tonight.herokuapp.com/beer/getBeerStatus', {headers: {Authorization : 'Bearer ' + token}}).then(
result => {
console.log('yey');
});
}
Error:
When I am using POSTMAN I am getting proper answer.
Postman input:
p.s. i already added :
app.use((req, res,next)=>{
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PATCH, DELETE');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorisation');
next();

You've written Authorisation:
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorisation');
But the header is Authorization as you have used with axios, try changing that and seeing if it works then,

I believe the cors error that you are receiving is from your node.js api. (https://beer-tonight.herokuapp.com/beer/getBeerStatus)
Since the host do are not the same origin (beer-tonight.herokuapp.com does not match with localhost), you need to enable cors for your node.js server.
If you are using express:
const express = require('express');
const cors = require('cors');
const app = express();
app.use(cors());
// ...
Source: here
Hapi.js:
server.connection({ routes: { cors: true } })
Source: here
Once you have CORS enabled, everything should work smoothly. More on CORS

Related

CORS Issue: Unable to send post request using NodeJs and Angular

I am getting this message when trying to send a post request:
Access to XMLHttpRequest at 'http://localhost:3002/api/products/checkout' from origin
'http://localhost:4200' has been blocked by CORS policy: Request header field content-type
is not allowed by Access-Control-Allow-Headers in preflight response.
Right now I'm simply trying to send data to my backend and then log it in the console. Get requests work fine but for some reason I get that CORS error when trying post. Here is my code:
Angular code:
//api call
return this.http.post('http://localhost:3000/api/checkout', cart)
NodeJs code:
const bodyParser = require('body-parser');
const express = require('express');
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use((req, res, next) => {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader(
'Access-Control-Allow-Header',
'Origin, X-Requested-With, Content-Type, Accept');
res.setHeader(
'Access-Control-Allow-Methods',
'GET, POST, PATCH, DELETE, OPTIONS');
next();
})
app.post("/api/checkout", (req, res, next) => {
const cart = req.body;
console.log(cart)
res.status(201).json()
})
module.exports = app;
In the network calls I can see that Request Headers is:
Access-Control-Request-Headers: content-type
while Response Headers is:
Access-Control-Request-Headers: Origin, X-Requested-With, Content-Type, Accept
I'm not sure if content-type being lower case has anything to do with the issue.
You should use req.set instead, just change setHeader to set only. Here is the document https://expressjs.com/en/api.html#res.set
And if you just using localhost, there's another easier option, you can use proxy. More information can be found here https://angular.io/guide/build#proxying-to-a-backend-server
I think the problem that you wrote Access-Control-Allow-Header instead of Access-Control-Allow-Headers, but I cannot test it now.
Be aware that you need to serve OPTIONS requests too. Which is just responding with an empty message body using the same headers. You can get these kind of OPTIONS requests before PUT, PATCH, DELETE from certain HTTP clients e.g. from browsers too.

How to solve CORS error "No 'Access-Control-Allow-Origin' header is present" in nodejs?

I have developed a MERN stack project which needs OAuth token from facebook. In order to get the access code from facebook, I am calling the backend api getAccessCode. Below is my api impementation,
const bodyParser = require('body-parser');
const express = require('express');
const router = require('express').Router();
const {FB} = require('fb')
const QueryString = require('query-string')
const app = express();
const env = require('dotenv').config()
const constants = require('../common/constants')
const cors = require('cors')
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended: true}))
app.use(cors())
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET,POST,DELETE');
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested With, Content-Type, Accept');
next();
});
router.route('/getAccessCode').post((request, response)=> {
const stringifiedParams = QueryString.stringify({
client_id : process.env.CLIENT_ID,
redirect_uri : process.env.REDIRECT_URI,
scope : [constants.EMAIL, constants.USER_PHOTOS],
response_type : constants.CODE,
auth_type : constants.RE_REQUEST,
display : constants.POPUP
})
const fbURL = process.env.ACCESS_CODE_URL + stringifiedParams
return response.redirect(fbURL)
})
By following several similar questions, I have found that I need to enable CORS. Therefore, I enabled the cors policy as in the above code. But still when I send a post request from my frontend, it gives the following error,
Access to XMLHttpRequest at 'https://www.facebook.com/v11.0/dialog/oauth?auth_type=rerequest&client_id=111111111111111&display=popup&redirect_uri=http%3A%2F%2Flocalhost%3A3000%2F&response_type=code&scope=email&scope=user_photos' (redirected from 'http://localhost:8000/fb/getAccessCode') from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
www.facebook.com/v11.0/dialog/oauth?auth_type=rerequest&client_id=11111111111111111&display=popup&redirect_uri=http%3A%2F%2Flocalhost%3A3000%2F&response_type=code&scope=email&scope=user_photos:1 Failed to load resource: net::ERR_FAILED
createError.js:16 Uncaught (in promise) Error: Network Error
at createError (createError.js:16)
at XMLHttpRequest.handleError (xhr.js:84)
Below is my request which is written in frontend,
axios.post("http://localhost:8000/getAccessCode")
Can someone please help me to solve this issue? Thanks in advance!
On frontend you're making a request with axios. axios makes the request under the hood, i.e. your browser's Location header is not set. So when you redirect the request, it turns into a cross-site request, because you're still on the same domain as you were before, while trying to request data from facebook via javascript.
What you can do is either:
Not use axios request to fetch the URL, you can build the URL in the frontend and navigate user to that URL (with <a href= or a button or programmatically, whatever you prefer).
OR
If you must fetch the URL string from backend, then just do that, nothing more. No need to redirect the request from the backend. So in your code, express should return res.status(200).json({ fbURL });. And in your axios's response handler, you should programmatically navigate the user to the facebook page for authentication: window.location = res.data.fbURL;

CORS blocking axios request with 'Authorization' Header and Data

Trying to send an axios post request from a Vue app (localhost) to my nodejs API (both localhost and heroku).
There are no issues receiving the response if the request is sent without data or headers, but as soon as I add them I get the following error:
Access to XMLHttpRequest at 'https://myapp.herokuapp.com/myendpoint' from origin 'http://localhost:8080'
has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No
'Access-Control-Allow-Origin' header is present on the requested resource.
I have tried different options, both server and client side, as suggested on similar questions but had no success.
Client Request:
const apiUrl = 'https://myapp.herokuapp.com/myendpoint'
//const apiUrl = 'http://localhost:5000/myendpoint'
const token = Buffer.from(`${this.userid}:${this.password}`).toString('base64')
const data = {
'mydata': 'some data'
}
axios.post(apiUrl, data, {
headers: {
Authorization: "Basic " + token
}
}).then( res => {
console.log(res)
}).catch( err => {
console.log(err)
})
Server Endpoint:
app.post("/myendpoint", (req, res) => {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Methods", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
res.send('This is the API\'s response')
})
Some of the answers I tried:
Response to preflight request doesn't pass access control check
Nodejs Express CORS issue with 'Access-Control-Allow-Origin'
https://www.moesif.com/blog/technical/cors/Authoritative-Guide-to-CORS-Cross-Origin-Resource-Sharing-for-REST-APIs/
CORS authorization issue while using axios
How to send authorization header with axios
I think it is better if you define your cors using a global middleware. First off, install cors by using npm i cors.
Then, I'll show an example of how that package could be used.
const express = require('express');
const cors = require('cors');
const app = express();
app.use(cors());
// your routes and things here...
Then, ensure that your front-end also uses withCredentials set to true in the axios request. This is done to ensure that the header is being sent properly.
axios.post(apiUrl, data, {
headers: {
Authorization: "Basic " + token
},
withCredentials: true,
}).then(() => ...);
Sometimes, if you define Access-Control-* manually, you might forget something. That's why I recommend you to use cors.

CORS Error : Response to preflight request doesn't pass access control check: It does not have HTTP ok status

I don't know what is causing this error. I set all the right headers and all the correct methods. This is my Node Js Server:
Full Error : login:1 Access to XMLHttpRequest at 'http://localhost:3000/' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status. zone-evergreen.js:2845 POST http://localhost:3000/ net::ERR_FAILED
const path = require("path");
const express = require("express");
const bodyParser = require("body-parser");
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use((req, res, next) => {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader(
"Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept"
);
res.setHeader(
"Access-Control-Allow-Methods",
"GET,PUT, POST, PATCH, DELETE, OPTIONS"
);
next();
});
I am sending POST request from an Angular app from http://localhost:4200 and connecting it with a MongoDB Server.
If someone could help me with this it would be great.
There are several ways to fix/workaround this.
Turn off CORS. For example: https://stackoverflow.com/questions/3102819/disable-same-origin-policy-in-chrome
Use a plugin for your browser : https://chrome.google.com/webstore/detail/allow-cors-access-control/lhobafahddgcelffkeicbaginigeejlf?hl=en
Use a proxy such as nginx. http://nginx.org/en/docs/beginners_guide.html
Go through the necessary setup for your server. This is more a
factor of the web server you have loaded on your EC2 instance
(presuming this is what you mean by "Amazon web service"). For your
specific server you can refer to the enable CORS website.

MERN: Cant connect React to Backend due to CORS error [duplicate]

This question already has answers here:
How to resolve 'preflight is invalid (redirect)' or 'redirect is not allowed for a preflight request'
(6 answers)
Closed 2 years ago.
I have built a microservice backend deployed on kubernetes on Digital Ocean.
I am trying to connect my react code to the backend and getting the below error:
Access to XMLHttpRequest at 'http://cultor.dev/api/users/signin' from origin 'http://localhost:3000'
has been blocked by CORS policy: Response to preflight request doesn't pass access control check:
Redirect is not allowed for a preflight request.
Index.ts settings:
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', '*');
res.header('Access-Control-Request-Headers', '*');
if (req.method === "OPTIONS") {
res.header('Access-Control-Allow-Methods', '*');
return res.status(200).json({});
}
next();
});
I would really appreciate the help. Thanks!
Install the cors middleware with
npm install cors
And you can use it directly like this:
const cors = require('cors');
app.use(cors());
Or you can set specific options like this:
const cors = require('cors');
const corsOpts = {
origin: '*',
credentials: true,
methods: ['GET','POST','HEAD','PUT','PATCH','DELETE'],
allowedHeaders: ['Content-Type'],
exposedHeaders: ['Content-Type']
};
app.use(cors(corsOpts));
You can replace origin with your website and allowedHeaders with the headers you're going to use.
I suggest trying to use cors middleware instead of puting the headers by yourself. Maybe you're missing something. You can download cors middleware from npm and use it in your express app
const cors = require('cors')
app.use(cors())

Resources