ExpressJS Different Domain Name - CORS - node.js

I am having a challange currently setting the domain for a cookie I am sending with the response from my expressjs implementation but currently it is only setting the IP address of where my expressjs server is at(the end point).
Here is my initial CORS configuration;
router.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "http://localhost:3000");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With,
Content-Type, Accept, pwd, email");
next();
});
Here is my res.cookie line inside my authentication part;
res.cookie('token', token, {domain: "localhost", expires: new
Date(Date.now() + 600000*100000), httpOnly: true});
When I log in using chrome, very oddly I get the cookie but under the IP address of my expressjs endpoint, lets say "http://88.13.91.0" so when I refresh I lose it. I also dont see in the response for the expressjs api the "set-cookie" header in the response, but I do get the cookie. I have cleared the cookie to make sure its coming after attempting to log in so I know its not stale. I also have in my fetch call "credentials" set to "include" as documented but no luck.
My question is, am I not able to set the domain if its not the same as the endpoint? My thought is that maybe this is a security issue and as a result blocked because no one should be able to set a cookie for a domain that isn't theres, or maybe I am wrong.

Try CORS like this and
import * as cors from "cors";
// or
const cors = require ('cors');
app.get("/", function (req, res) {
res.setHeader("Content-Type", "application/x-www-form-urlencoded");
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader(
"Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept"
);
res.setHeader("Access-Control-Allow-Credentials", true);
add this above all your middleware
app.use(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.

Setting Cross-origin-Embedder-Policy and Cross-origin-Opener-Policy headers in nodejs

I've been developping a website using express(NodeJS) for the backend and React for the frontend. I've come accross the issue where my application won't work on Firefox due to this error "ReferenceError: SharedArrayBuffer is not defined".
After having searched a bit online, it appears it has to do with CORS. I saw that on Chrome there is a warning about the use of SharedArrayBuffer as well.
So I read that I need to set those headers
Ì€Cross-Origin-Opener-Policy: same-origin Cross-Origin-Embedder-Policy: require-corp
But I am not sure on how to do that. On my backend I've been using the cors package to set my cors headers and options as such
const corsOptions = {
origin: process.env.CLIENT_URL,
credentials: true,
'allowedHeaders': ['sessionId', 'Content-Type'],
'exposedHeaders': ['sessionId'],
'methods': 'GET,HEAD,PUT,PATCH,POST,DELETE',
'preflightContinue': false
}
app.use(cors(corsOptions));
I've also tried using this method but it doesn't appear to work either :
app.use((req, res, next) => {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content, Accept, Content-Type, Authorization');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, PATCH, OPTIONS');
res.setHeader('Cross-origin-Embedder-Policy', 'require-corp');
res.setHeader('Cross-origin-Opener-Policy','same-origin');
next();
});
Am I totally missing something/misunderstanding?
It is my first time developping a web application and I am kind of lost at this point. Any help would be grately appreciated.
Thank you
Not sure what causes this, but for me using a different route worked
Cross-origin isolation using node / express
app.use(function(req, res, next) {
res.header("Cross-Origin-Embedder-Policy", "require-corp");
res.header("Cross-Origin-Opener-Policy", "same-origin");
next();
});
app.get('/', async (req, res) => {
res.sendFile(path.join(__dirname, 'public/index.html'));
});
// does **not** work, no cors headers in response
app.get('/app', async (req, res) => {
res.sendFile(path.join(__dirname, 'public/index.html'));
});
// does work, cors headers in response as expected
try to process options request in your custom middleware
app.use((req, res, next) => {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content, Accept, Content-Type, Authorization');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, PATCH, OPTIONS');
res.setHeader('Cross-origin-Embedder-Policy', 'require-corp');
res.setHeader('Cross-origin-Opener-Policy','same-origin');
if (req.method === 'OPTIONS') {
res.sendStatus(200)
} else {
next()
}
});
The Cross-Origin-Embedder-Policy and Cross-Origin-Opener-Policy must be set on the client website (client.example.com), i.e. the one consuming the backend resources.
The backend (api.example.com) should be setup to allow for CORS (for example using the cors package as you are) from the client's origin.
Access-Control-Allow-Origin: client.example.com
If you are embedding images or link from the backend, then you would need to add the crossorigin="anonymous" attribute.
<img src="api.example.com/image.png" crossorigin="anonymous" alt="" />
If you are embedding an iframe, then the target of the iframe would need to add the Cross-Origin-Resource-Policy: cross-origin and Cross-Origin-Embedder-Policy: require-corp headers on the backend (api.example.com) to allow other websites to embed from that resource. Note that this means anyone would be able to embed from your backend.
Note that I am not sure how this relates to the SharedArrayBuffer exception you are seeing.

How to set an "Access-Control-Allow-Origin" header to only allow one certain computer

I have a some node.js code in a glitch server (not in my own computer) :
let http = require("http");
http.createServer((req, res) => {
res.writeHead(200, {
"Allow-Access-Control-Origin": "http://my-localhost-IP-Address"
});
res.end(someData)
})
That doesn't seem to work for me.
I can't do it from my localhost, nor can I do it in the file: protocol, but I can make it by simply typing the url in the browser.
Setting Access-Control-Allow-Origin to http://localhost doesn't work either.
Is there a way I can set the "Access-Control-Allow-Origin" header to only allow some specific computers to access it.
Note: Again, the code is in a server in the internet, not in my own computer.
You can use CORS
let cors = require("cors");
app.use(cors(), function(req, res, next) {
res.header("Access-Control-Allow-Origin", "http://localhost:4200"); // 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();
});
In this, you can also add multiple URLs.

Cannot make requests on external URLs outside my localhost

I get this error when making a GET over 'https://www.google.com/'.
Failed to load https://www.google.com/: 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:4200' is therefore not allowed access. The response had HTTP status code 405.
On server side I use cors:
server.use(cors({
origin: '*',
credentials: true
}));
server.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With,
Content-Type, Accept");
next();
});
server.all('/*', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
next();
});
On client side I have a cookieService:
getCookies(URL) {
const headers = new Headers();
**headers.append('Access-Control-Allow-Origin', '*');**
return this.http.get(URL, { headers: headers }).map(res => res.json());
}
On an angular component I call this function:
searchCookies() {
this.cookieService.getCookies('https://www.google.com').subscribe();
}
Is there a way to add this header to the GET response? Or is there another way to acces to an external URL like https://www.google.com?
Thanks! :)
CORS headers, which you are adding to localhost via your server response, do not work for google - the whole idea of CORS is that the 3rd party server (in this case https://google.com) can defend itself from Cross Origin Resource Sharing.
TL;DR - https://google.com doesn't allow localhost to access the website. If you want to scrape the website - you'd have to access it from node.js itself, rather than client-side JS.

Google Maps API, fetch method having CORS issue

As stated in the title of this question, i'm having CORS issues with a fetch method. Here are the solutions i've tried. Obviously none have worked.
Actual console error:
No 'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://localhost:3000' is therefore not allowed
access. If an opaque response serves your needs, set the request's
mode to 'no-cors' to fetch the resource with CORS disabled.
I tried to fix the issue via my Express server. I am configuring this before I establish my routes.
import cors from 'cors';
app.use(cors({
origin: '*',
}));
Also tried it this way.
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();
});
Client side service. Set {mode: 'cors'} object.
fetch(requestUrl, {mode: 'cors'}).then((response) => {
return response.json();
}).then((restaurants) => {
resolve(restaurants);
}).catch((err) => {
reject(err);
});
At this point, i'm lost. I'm just trying to get data back from google maps api. Any help would be grateful.

Resources