CORS preflight channel did not succeed, React to Express - node.js

When sending a request over CORS from my React app to my Node.JS and Express.js backend i get an:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:3001/students/login. (Reason: CORS preflight channel did not succeed).
Im using axios for sending out requests and this is the request configuration:
({ email, password }) => {
return axios.post(API_ENDPOINT + UCENIK.post.login,
{ email, password },
{
withCredentials: true,
Headers: {
'Content-Type': 'application/x-www-form-urlencoded',
}
})
}
I have tried allowing CORS in Express with these headers:
app.use(function (req, res, next) {
res.header("Access-Control-Allow-Origin", req.headers.origin);
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization')");
res.header("Access-Control-Allow-Credentials", true);
res.header("Access-Control-Allow-Methods", "GET, PUT, POST, DELETE, OPTIONS");
next();
});
Edit: fixed using npm Cors module and providing this object for settings:
{
origin: 'http://localhost:3000',
cors: true
}

I assume this is only a development problem, because your express instance and reactjs frontend server run on a different port. In the production environment this probably isn't the case.
In stead of using CORS in your development cycle try to proxy the request from your frontend server to your express server.
For exmple the webpack devserver has a seperate proxy configuration https://webpack.js.org/configuration/dev-server/#devserver-proxy

Related

Cors Exception in Node.js

I am having cors error in a Node.js application as follows:
Access to XMLHttpRequest at 'http://localhost:8081/api/tutorials/1' from origin 'http://localhost:2240' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The 'Access-Control-Allow-Origin' header has a value 'http://localhost:8081' that is not equal to the supplied origin.
tutorial.component.js:91 Error: Network Error
at createError (createError.js:16:1)
at XMLHttpRequest.handleError (xhr.js:117:1)
xhr.js:210 PUT http://localhost:8081/api/tutorials/1 net::ERR_FAILED
The above are the messages from browser console. To avoid them, in the server-side with Express.js did the followings:
var corsOptions = {
origin: "http://localhost:8081"
};
app.use(cors(corsOptions));
app.use(function(req, res, next) {
//Website you wish to allow to connect
res.setHeader('Access-Control-Allow-Origin', '*');
//Request methods you wish to allow
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
//Request headers you wish to allow
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
//Pass to next layer of middleware
next();
});
This actually occurs when I am trying to update an item in the database. So using axios, I am doing the following to do http request as follows:
import axios from "axios";
export default axios.create({
baseURL: "http://localhost:8081/api",
headers: {
"Content-type": "application/json"
}
});
But still couldn't sort this out. Any way to resolve it in the proper way?
The CORS origin should be the domain of the site that is connecting to the server, not the server's address.
Change the port to 8080 or whatever port your site is running on:
var corsOptions = {
origin: "http://localhost:8080"
};
This allows the browser to ensure that it only connects to the server from sites that are trusted.

Cors error strict-origin-when-cross-origin simple nodeJS-reactJS project

I'm trying to upload image to Cloundinary, but an error occurred with status code 500 relating to cors though i had set the server to allow all origin.
The error message is:
POST http://localhost:5000/my-route-upload 500 (Internal Server Error)
here is my POST function :
const cloudinaryUpload = (fileToUpload) => {
return axios.post(API_URL + '/cloudinary-upload', fileToUpload)
.then(res => console.log(res))
.catch(err => {
console.log(err)
console.log("cannot post")
}); }
In server side, I had added the following block in App.JS
const cors = require('cors');
var app = express();
app.use(cors({
origin: "*",
})
);
Those codes did execute, i tried modify the origin to the specific one like http://127.0.0.1:3001 (my client port is 3000). Then it came out another error message
Back to the first error, in tab Network/Headers :
Request URL: http://localhost:5000/cloudinary-upload
Request Method: POST
Status Code: 500
Referrer Policy: strict-origin-when-cross-origin
Access-Control-Allow-Origin: *
Host: localhost:5000
Origin: http://127.0.0.1:3000
I don't know why it didn't work. I use create-react-app for client and Express generator for server
Maybe you should add the content-type header to your Axios request. Like this.
const res = await axios.post('url', data, {
headers: {
'content-type': 'application/json'
}
});
Setup a proxy for your server from your client
Proxy can be a simple
"proxy": "http://localhost:5000" in your package.json, where all unknown requests will be proxied to localhost:5000
Essentially you need to call the api from client as /my-route-upload instead of http://localhost:5000/my-route-upload.
But preferred method would be to add a file called src/setupProxy.js
and
$ npm install http-proxy-middleware --save
add this to the file
module.exports = function(app) {
app.use(
'/api',
createProxyMiddleware({
target: 'http://localhost:5000',
changeOrigin: true,
})
);
};```
Also look at enabling cors in express
https://enable-cors.org/server_expressjs.html
const cors = require('cors');
var app = express();
app.use(cors());
try this
This middleware helps to avoid cross-platform error
app.use((req, res, next) => {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader(
"Access-Control-Allow-Methods",
"OPTIONS, GET, POST, PUT, PATCH, DELETE"
);
res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
next();
});
Set this header middleware on your root file above your all routes in the express app, Update this code block with your server cors block in AppJS

How to resolve cors origin exception

We deployed our nodejs app to aws ,but it is giving this error while accessing any api,
Access to XMLHttpRequest at 'https://vkluy41ib9.execute-api.ap-south-1.amazonaws.com/dev/api/auth/login' from origin 'https://cmc-app.netlify.app' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Now the issue if our node app is hosted on localhost its working fine but deploying on live server its throwing error
this is our code :
app.options(cors());
app.use(function (req, res, next) {
//Enabling CORS
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT");
res.header(
"Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept, x-client-key, x-client-token, x-client-secret, Authorization"
);
next();
})
If you want to use cors() then you need to write:
app.options("*", cors());
otherwise it will not be registered correctly. Using this method, the handler returned from cors() will be used on all OPTIONS-requests.
The second part where you do app.use is not necessary, because it does nearly the same as the method before.
To get the result you wanted with the second part, you could write:
app.options("*", cors({
methods: ["GET", "HEAD", "OPTIONS", "POST", "PUT"],
allowedHeaders: ["origin", "X-Requested-With", "Content-Type", "Accept", "x-client-key", "x-client-token", "x-client-secret", "Authorization"]
}));
All configuration options for cors are listed here: https://www.npmjs.com/package/cors#configuration-options

CORS "It does not have HTTP ok status."

NodeJS Express platform. Using Zeit Now 2. Cannot use server.js as proxy to send from backend to prevent CORS. So, nor wrestling with CORS problems. Tested desktop: chrome, safari, firefox. Mobile: chrome, firefox. Have tested to host on Now with HTTPS, same error as I get locally on both localhost:3000 and 127.0.0.1:3000, same using port 80.
Access to fetch at 'https://**MY_URL**/user/login' from origin 'http://127.0.0.1:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
I use https://www.npmjs.com/package/cors to set my CORS configs:
app.use(cors({
'allowedHeaders': ['Content-Type', 'API-Key', 'API-Secret', 'Access-Control-Allow-Headers'', 'accept', 'client-security-token'],
'exposedHeaders': ['sessionId'],
'origin': '*',
'methods': 'GET, HEAD, PUT, PATCH, POST, DELETE, OPTIONS',
'preflightContinue': false,
'credentials': true
}));
The CORS settings doesn't seem to work for my, so I tried with the now.json file, like this (trimmed veersion):
{
"name": "my-test-api",
"version": 2,
"routes": [
{
"src": "/.*",
"methods": ["GET", "POST", "OPTIONS"],
"headers": { "Access-Control-Max-Age": "1000", "Access-Control-Allow-Methods": "GET, HEAD, PUT, PATCH, POST, DELETE, OPTIONS", "Access-Control-Allow-Origin": "*", "Accept": "text/plain", "Content-Type": "text/plain", "Access-Control-Allow-Headers": "sessionId, Content-Type, API-Key, API-Secret, Access-Control-Allow-Headers", "Access-Control-Expose-Headers": "sessionId", "Access-Control-Allow-Credentials": "true" },
"continue": true
},
{ "src": "/user/login", "methods": ["POST"], "dest": "index.js" }
]
}
Even added statusCode 200 to all my responses, but without any success. Removing the Npm-cors-package won't change anything, but removing the Now.json totally destroys stuff, and I get this error, from MDN even though I have it specified in my app.use(cors()).
Not really sure what to do, have been struggeling with this forever. No problem with cURL or other hosts where I can use backend proxy.
You may need to enable pre-flight requests for your route
app.use(cors())
app.options('/post/login', cors()) // enable pre-flight requests
app.post('/post/login', (req, res, next) => {
// your code here
});
or for all routes
app.options('*', cors())
You can set the HTTP status of the pre-flight response.
app.options('*', function (req,res) { res.sendStatus(200); });
I got this cryptic error when the preflight (OPTIONS) request returned a 404. I eventually found I was using an incorrect path, and my router (Golang httprouter) 404s OPTIONS for non-existent routes.
you can use nginx's reverse proxy to proxy your 80 port's requests to 3000 port and it will work fine
Please try by adding one line and remove your old cors config from express and now.json
app.use(cors());
That’s it. CORS is now enabled.
If you make a request to your app, you will notice a new header being returned:
Access-Control-Allow-Origin: *
I use Nginx for cors configuration. But for local development in docker it's better to use express middleware:
const corsMiddleware = (req, res, next) => {
res.header('Access-Control-Allow-Origin', '*')
.header('Access-Control-Allow-Headers', 'Authorization,Accept,Origin,DNT,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range')
.header('Access-Control-Allow-Methods', 'GET,POST,OPTIONS,PUT,DELETE,PATCH');
if (req.method === 'OPTIONS') {
res.sendStatus(200);
} else {
next();
}
}
app.use(corsMiddleware);
https://cors-anywhere.herokuapp.com/yoururl
Example:
axios.get('https://cors-anywhere.herokuapp.com/spo.handball4all.de/Spielbetrieb/index.php?orgGrpID=56&score=45991')
.then(response => {
const $ = cheerio.load(response.data);
})

How to pass cookies through CORS?

I have a project that sends HTTP requests from the client using Axios
axios.create({
baseURL: `http://localhost:8081/`,
withCredentials: true
})
And I suppose this allows cookies -Which I am sure it shows in the browser before you ask- to be sent with the requests.
The problem occurs in the back-end, when this error shows in the log:
Response to preflight request doesn't pass access control check: The
value of the 'Access-Control-Allow-Origin' header in the response must
not be the wildcard '*' when the request's credentials mode is
'include'. Origin 'http://localhost:8080' is therefore not allowed
access. The credentials mode of requests initiated by the
XMLHttpRequest is controlled by the withCredentials attribute.
I tried this:
app.use(cors({
//origin : to be set later
credentials: true,
}))
and this instead:
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, Authorization");
res.header("Access-Control-Allow-Credentials", true);
next();
});
but neither seems to work.
EDIT - Here is the answer for future visitors
With the help of the participants in comments, I found out I had to set the origin value:
app.use(cors({
origin : "http://localhost:8080",
credentials: true,
}))
I know it's too late for OP, but for those who keep comming here - what helped me is:
app.use(cors({
preflightContinue: true,
credentials: true,
}));
source: https://expressjs.com/en/resources/middleware/cors.html
I got this problem and I fixed it by setting the header "Access-Control-Allow-Origin" to the URL of my frontend instead of "*"
More details: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS/Errors/CORSNotSupportingCredentials

Resources