This question already has answers here:
How to enable cors nodejs with express?
(10 answers)
Closed 3 years ago.
Im trying to get a text/html of an url differnt from origin, but i cant get a POST because a CORS block.
Im makeing the requisition in angular this way:
const express = require('express');
const cors = require('cors');
validateOperador(login,pass){
const url = `${this.operadoresValidateUrl}a=${login}&b=${pass}`
return this.http.get(url,{headers:
{'Content-Type': 'text/html', 'Access-Control-Allow-Origin': '*' } })
}
and my node backend using express, is configured this way:
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();
});
httpServer = http.createServer(app);
app.use(cors())
app.use(bodyParser.json())
app.use(compression());
Im getting this error:
Access to XMLHttpRequest at 'my api url' from origin 'my project url' 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.
This is not a duplicated question, because I´ve already installed and runned CORS
You must not add 'Access-Control-Allow-Origin': '*' from client side.
Also you are doing a GET and not a POST not sure if that's what you want.
Also it seems a duplicate of this
Install cors: npm install cors
const cors = require('cors');
Then use in your index.js
app.use(cors())
Related
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.
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.
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())
I'm making a request to Azure function on local
url = 'http://localhost:7071/api/saveGraphDataFlow'
save(body) {
let headers = new HttpHeaders()
headers.append('Content-Type', 'application/json')
return this.httpClient.post(this.url, body, { headers: headers }).pipe(
map(res => {
return res
})
)
}
On my express server I'm adding cors to response
const createHandler = require("azure-function-express").createHandler;
const express = require("express");
const routers = require("./routes/routes");
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.header("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE,OPTIONS");
next();
});
app.use("/api/", routers);
// Binds the express app to an Azure Function handler
module.exports = createHandler(app);
But when I send request I get this error :
Access to XMLHttpRequest at 'http://localhost:7071/api/saveGraphDataFlow' from origin 'http://localhost:4200' 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.
the preflight request is not passing
You could try to remove the extra slash from
app.use("/api/", routers);
and so it becomes:
app.use("/api", routers);
Also, as a sidenote, I have not seen your API router, and so maybe there is an extra slash or missing slash in there. Another thing I have noticed is that you're importing an entire folder (?) for your routers so make sure that you are importing a file at once. (i have not seen that, so this might not be true)
I am using a Angular 2 app and a NodeJS API. When I had the API in localhost everything was working just right, but I published my NodeJS API to a real server and it gives me that error when I try to access to any method of the API:
Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource
I was checking some anwsers from another topics here in stackoverflow and nothing has worked for me.
I've this snipped :
app.use(require("cors")());
app.use(function(req, res, next) {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader(
"Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept,responseType"
);
res.setHeader(
"Access-Control-Allow-Methods",
"POST, GET, PATCH, DELETE, OPTIONS"
);
next();
});
So I have the "*" in Access-Control-Allow-Origin header why I got the error that I don't have this header in my headers?
Thanks in advance.
Use only the middleware
var express = require('express')
var cors = require('cors')
var app = express()
app.use(cors())
more details