Facing CORS In Node framework NestJS-6.3.1 - nestjs

I am developing a Node base project using nestJs => 6.3.1 framework. I have enabled all cors still I am facing following error
Access to XMLHttpRequest at 'localhost:3000' from origin 'http://localhost:4200' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.
core.js:7187 ERROR HttpErrorResponse {headers: HttpHeaders, status: 0, statusText: "Unknown Error", url: "localhost:3000", ok: false, …}
I have tried the following ways but still facing the same issue.
1.
var app = await NestFactory.create(AppModule,{cors:true});
await app.listen(3000);
var app = await NestFactory.create(AppModule);
const options = {
origin: '*',
methods: 'GET,HEAD,PUT,PATCH,POST,DELETE',
preflightContinue: false,
optionsSuccessStatus: 204,
credentials: true,
allowedHeaders: 'Content-Type, Accept',
};
console.log(app);
app.enableCors(options);
await app.listen(3000);
import { NestFactory } from '#nestjs/core';
import { AppModule } from './app/app.module';
async function bootstrap() {
var app = await NestFactory.create(AppModule);
const options = {
origin: '*',
methods: 'GET,HEAD,PUT,PATCH,POST,DELETE',
preflightContinue: false,
optionsSuccessStatus: 204,
credentials: true,
allowedHeaders: 'Content-Type, Accept',
};
console.log(app);
app.enableCors(options);
await app.listen(3000);
}
bootstrap();
Expected output: Server should allow processing cros origin request but it gives following issue or error.
Access to XMLHttpRequest at 'localhost:3000' from origin 'http://localhost:4200' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.

Read the error message carefully:
Access to XMLHttpRequest at 'localhost:3000' from origin 'http://localhost:4200' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.
You aren't making a request over HTTP (or HTTPS) so your server (which is an HTTP server) can't be responding to it, so nothing you do to the code running your server will make a difference.
You need to change the code that requests a URL starting with localhost:3000 and change it to http://localhost:3000

Related

The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute wont work

I am having this problem when trying to use withCredentials that it tells me that I need
Access to XMLHttpRequest at 'http://localhost:3005/api/v1/user' from origin 'http://localhost:3000' has been blocked by CORS policy: 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'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
Uncaught (in promise) AxiosError {message: 'Network Error', name: 'AxiosError', code: 'ERR_NETWORK', config: {…}, request: XMLHttpRequest, …}
async function getUser() {
const user = await axios.get("http://localhost:3005/api/v1/user", {
withCredentials: true, headers: {
'Access-Control-Allow-Origin': '*', 'Content-Type': 'application/json'
}
});
console.log(user)
}
useEffect(() => {
getUser();
}, [])
Researching this people are telling me that I need to activate cors on the server. But from what I can tell I have already done that by doing this + npm I cors.
const cors = require('cors')
var app = express();
const corsOptions ={
origin:'*',
credentials:true, //access-control-allow-credentials:true
optionSuccessStatus:200,
}
app.use(cors(corsOptions))
If I remove the withCredentials everything works fine the problem is that I need the connect.sid cookie on the server in order to log in the user.
I have had this problem before. Solved it by changing the * to ['http://localhost:3000']
So your code should say:
const cors = require('cors')
var app = express();
const corsOptions ={
origin:['http://localhost:3000'],
credentials:true, //access-control-allow-credentials:true
optionSuccessStatus:200,
}
app.use(cors(corsOptions))

What to include in headers when making preflight complex CORS request?

An app I'm making has the front-end and node-back end hosted separately (cross origin). The front-end is making a call to the back end for login where the x-session-token is sent back. Because this is a custom header I understand this to be a complex request and therefore a pre-flight check is needed.
In the server.js file I have the following snippet (which I understand to enable CORS pre-flight checks):
const express = require('express');
const cors = require("cors");
const app = express();
const corsOptions = {
origin: true,
credentials: true
}
app.options('*', cors(corsOptions));
The front-end makes the following axios call:
axios.post('/api/user/login', logInObj,
{withCredentials:true},
{crossDomain:true},
{'Access-Control-Request-Headers': 'Content-Type'},
{'Access-Control-Request-Method': 'post'}
)
.then(logInResponse => ...
Which is responded to by this in the back-end:
router.post('/api/user/login', (request, response) => {
...
response.setHeader('Access-Control-Allow-Credentials', true);
response.setHeader('Access-Control-Allow-Headers', 'Content-Type');
response.setHeader('Access-Control-Allow-Method', 'get', 'post', 'options');
response.setHeader('Access-Control-Allow-Origin', request.get('Origin'));
response.setHeader('Access-Control-Max-Age','86400')
response.setHeader('Access-Control-Expose-Headers', 'Access-Control-Allow-Origin');
...
When I console log the response header on the back-end it contains:
An x-session-token matches that in MySQL
Access-Control-Allow-Origin is listed as http://localhost:3000 not wildcard (*)
However the console.log of the response in the browser has null for the session-token which tells me the browser is blocking the CORS return data (X-Session-Token in this case). What am I missing in the request or response header?
I think you miss the exposed Header you want to send back.
"x-session-token" ?
Also try to use app.use instead of just app.options and let the cors package handle it unless it is just specific to this route of course
app.use(cors({
credentials: true,
exposedHeaders: ['Set-Cookie', 'Content-Length', 'Accept', 'X-Requested-With', 'X-HTTP-Method-Override', 'x-session-token' ],
methods: ['GET', 'POST', 'OPTIONS', 'HEAD'],
optionsSuccessStatus: 204,
origin: 'http://localhost:3000'
})

express JS cors middleware does not work when server is accessed though fetch request

Server is on http://localhost:3001, and client is same, but with port 3000.
On client I run simple fetch, I need to get logged-in user data from server, and currently I am doing it just using GET method(GET, POST, none work) like this(I also have to include cookies):
fetch("http://localhost:3001/user", {
method: "GET",
credentials: "include",
headers: {
"Content-Type": "application/json"
}
}).then(response => {
console.log(response);
});
And the server:
const cors = require("cors");
var corsOptions = {
origin: "http://localhost:3000",
optionsSuccessStatus: 200
};
app.get("/user", cors(corsOptions), function(req, res, next) {
u_session = req.session;
const db_result = db
.collection("users")
.findOne({ email: u_session.email }, function(err, result) {
if (err) throw err;
res.json({ email: result.email, type: result.type });
});
});
What I get is cors error:
Access to fetch at 'http://localhost:3001/user' from origin 'http://localhost:3000' 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. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
Also if i go to server URL through browser, I can see access-allow-control-allow-origin header set successfully.
Also as requested, screenshot of failed case network tab:
I've searched plenty of solutions on the internet, nothing seems to work. Am I missing something?
Thanks for any help.
Ensure that if you have a proxy set that it is set to http://localhost:3001. After that adjust your fetch to only use a partial url like so:
fetch("/user", {
method: "GET",
headers: {
"Content-Type": "application/json"
}
}).then(response => {
console.log(response);
});
it should be safe to remove this as well:
const cors = require("cors");
var corsOptions = {
origin: "http://localhost:3000",
optionsSuccessStatus: 200
};
Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
What sticks out to me is "preflight". I think it may be the OPTIONS request that doesn't have the correct CORS headers enabled. Ensure that you're enabling CORS on GET, POST, OPTIONS, and any other method your API supports.
Since you send credentials from the client, you must configure your cors module to allow credentials via athecredentials property. Also, application/json is a non-simple Content-Type, so you must allow that explicitly via allowedHeaders:
var corsOptions = {
origin: "http://localhost:3000",
optionsSuccessStatus: 200,
credentials: true,
allowedHeaders: ["Content-Type"]
};
Without this, the server will not include a Access-Control-Allow-Credentials header in the OPTIONS preflight, and the browser will refuse to send the main GET request.

nodejs cross-origin read blocking issue with image resources and canvas

I have a nodejs application were cors setup is done using cors package from expressjs.
My cors setup code is :
var whitelist = ['https://shajao.com', 'https://www.shajao.com'];
var corsOptions = {
origin: function (origin, callback) {
if (whitelist.indexOf(origin) !== -1) {
callback(null, true)
} else {
callback(new Error('Not allowed by CORS'))
}
},
allowedHeaders: ['Content-Type', 'Authorization', 'Content-Length', 'X-Requested-With', 'Accept'],
methods: ['GET', 'PUT', 'POST', 'DELETE', 'OPTIONS'],
optionsSuccessStatus: 200 // some legacy browsers (IE11, various SmartTVs) choke on 204
}
app.use(cors(corsOptions));
app.use(express.static(path.join(__dirname, '/public/')));
apis are called from an angular application which is getting server reponses perfectly. So cors is working nicely here. But image resources are getting blocked by cors.
Url to visit if you want to see the problem :
https://shajao.com/frames
Sample image url: https://api.shajao.com/uploads/frames/8cf9006f-0225-461b-a4f2-153737152274.png
Cross-Origin Read Blocking (CORB) is a new web platform security feature.
Ref : https://www.chromium.org/Home/chromium-security/corb-for-developers
Try clearing browser's cache first.
If it doesn't work you will have to set the correct "Content-Type" header for the response.

Enabled CORS in node/express but getting "Response to preflight request doesn't pass access control check"

I am getting the error :
Failed to load http://localhost:3000/users/register: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access.
On the front end i'm using axios:
const instance = axios.create({
baseURL: 'http://localhost:3000',
timeout: 1000,
headers: {"Access-Control-Allow-Origin": "*"}
});
instance.post('/users/register').then((res) => {
console.log(res);
}).catch((err) => {
console.log(err);
});
and on the server-side using express i am using cors:
var cors = require('cors');
var corsOptions = {
origin: '*',
optionsSuccessStatus: 200
}
app.use(cors(corsOptions));
I am getting a response code of 200 and I do see the 'Access-Control-Allow-Origin' header but i'm not getting anything on the server-side. Any ideas?
You most likely need to also explicitly enable support for OPTIONS requests (i.e. "CORS preflight"). See https://github.com/expressjs/cors#enabling-cors-pre-flight for details on how to do that.
For your specific case, I would add the following:
app.options('/users/register', cors(corsOptions));
Or if you want to enable it for all requests:
app.options('*', cors(corsOptions));

Resources