CORS was working fine but suddenly stopped working? - node.js

This is what I have in Node:
app.use(function (req, res, next) {
// Website you wish to allow to connect
res.setHeader('Access-Control-Allow-Origin', 'http://localhost:4200/');
// 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');
// Set to true if you need the website to include cookies in the requests sent
// to the API (e.g. in case you use sessions)
res.setHeader('Access-Control-Allow-Credentials', true);
// Pass to next layer of middleware
next();
});
My front-end is in Angular. Everything was working just fine, but all of a sudden I started getting CORS errors. When I check the console, I get this:
The Initiator Context and the Allowed Origin are exactly the same. And, as I mentioned before, I was having 0 issues until all of a sudden it decided to stop working. So I don't understand what's going on here. Any help will be appreciated.

You can try with http://localhost:4200, without the last '/'

Related

405 (Method Not Allowed) - PUT

I am currently taking a NodeJS course and learning GraphQL.
The course instructed to set header on the server side like this:
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');
if (req.method === 'OPTIONS') {
return res.sendStatus(200);
}
next();
However it keeps giving me a
App.js:122 PUT http://localhost:8080/graphql 405 (Method Not Allowed)
error.
I tried looking at the video multiple times and looking around for answers but found no luck.
Setting the response header Access-Control-Allow-Methods: ..., PUT, ... tells the browsers to allow cross-origin clients, i.e. a 3rd-party website from another domain, to send PUT requests to your backend service. This has nothing to do with the error response 405 (PUT) Method not allowed.
The error 405 (PUT) Method not allowed is returned by your Nodejs app because there is no actions to handle PUT requests to that path in your code.
GraphQL libraries typically use POST. Try sending POST requests to your GraphQL endpoint instead of PUT.

Access to XMLHttpRequest problems with Cors

I took an Ionic 5 course and when I did one of the exercises I wanted to put the backend written in JS inside github and heroku, when starting my authentication within my application it throws me the following error:
error
my backend is en node and express:
//allow cross config
server.app.use( cors({ origin: true, credentials: true }) );
server.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-token, content-type');
next();
});
my app need to login and return one token per user, and this token is use in headers in other petitions
To avoid CORS issues i think you should use native http requests in your ionic app.
That is the simpliest way to solve your issue in my point of view.

How to solve the issue response to preflight request doesnt pass access control check error?

I have a angular code in a VM, node code in another VM. I need to make an API call from this angular VM to node VM. I have included the cors module also. But still while making an API call, getting an error like
"access to xmlhttprequest at 'http:IP1' from origin 'http:IP2' has been blocked by CORS policy: Response to preflight request doesnt pass access control check: No 'Access control".
I have set header like this also,
app.use(function(req,res,next) {
res.setHeader('Access-Control-Allow-Origin','*');
res.setHeader('Access-Control-Allow-Methods','POST');
res.setHeader('Access-Control-Allow-Headers','X-Requested-With,content-type');
res.setHeader('Access-Control-Allow-Credentials',true);
next();
});
app.use(cors());
But still I'm facing an error. Can anybody tell me how to solve this error?
Try to set explicitly your localhost and add desired types of methods:
// Add headers
app.use(function (req, res, next) {
// Website you wish to allow to connect
res.setHeader('Access-Control-Allow-Origin', 'http://localhost:4200');
// desired types of methods
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
// Set to true if you need the website to include cookies in the requests sent
// to the API (e.g. in case you use sessions)
res.setHeader('Access-Control-Allow-Credentials', true);
// Pass to next layer of middleware
next();
});
UPDATE:
For example, your node server is hosted at http://127.0.0.1:8000. Then your Angular Application should be http://127.0.0.1:4200.
UPDATE 1:
npm install --save cors
and then:
var express = require('express');
var cors = require('cors');
var app = express();
app.use(cors());

Failed to load 'endpoint': Request header field If-Modified-Since is not allowed by Access-Control-Allow-Headers in preflight response

I have created one API service using nodejs and it is working fine when I accessing through the browser. But when I'm try to call it from web application (MEAN app), getting the "Failed to load http://localhost:2020/api/posts: Request header field If-Modified-Since is not allowed by Access-Control-Allow-Headers in preflight response" issue.
Following code is added in index.js of the API service.
// Add headers
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');
// Set to true if you need the website to include cookies in the requests sent
// to the API (e.g. in case you use sessions)
res.setHeader('Access-Control-Allow-Credentials', true);
// Pass to next layer of middleware
next();
});
and added following lines in controller of the web app,
app.config(["$routeProvider", "$httpProvider", function ($routeProvider, $httpProvider) {
$httpProvider.defaults.headers.common['Access-Control-Allow-Headers'] = '*';
}
]);
But no luck for added the above lines. How to resolve this issue ?
Thanks.
You need to add If-Modified-Since to Access-Control-Allow-Headers in your server code:
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type,If-Modified-Since');
Also the part where you touch HTTP header on client seems useless to me, I don't think you can do anything with that.

Angular on localhost gets 404 when consuming GET api from different localhost PORT - CORS issue?

Ever since I switched to the database URL from the in-memory-web-api URL, the Angular app's JavaScript console gives me a 404 error
JavaScript console output 404 error
I've got my angular app running on lite-server using localhost:3035/
I've got a mongodb/nodejs/express database running on localhost:3039/
My angular app was "GET"-ing just fine using the in-memory-web-api url 'api/loggerData'
Any thoughts? Is it CORS? Something else? Do I need to configure the lite-server on the angular side as well?
Here's my angular Code:
private loggerUrl = 'localhost:3039/read/getall/';
getLoggerData(): Promise <Dataset[]> {
return this.http.get(this.loggerUrl)
.toPromise()
.then(response => response.json().data as Dataset[])
.catch(this.handleError);
}
Also, I've tried implementing some CORS solutions on the database side that haven't affected anything -
here's some of the database code I modified:
var app = express();
app.use(function (req, res, next) {
//Website you wish to allow to connect
res.setHeader('Access-Control-Allow-Origin', 'http://localhost:3035');
// 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');
// Set to true if you need the website to include cookies in the requests sent
// to the API (e.g. in case you use sessions)
res.setHeader('Access-Control-Allow-Credentials', true);
// Pass to next layer of middleware
next();
});
No collection errors usually means, that you have left hanging some the equivalent of:
InMemoryWebApiModule.forRoot(InMemoryDataService)
in your ngModule, which interferes when you try and make "real" http-requests. So remove that from your ngModule and you should be good to go! :)
After this you might still run into problems with CORS, but this should fix the current error you get :)
And as mentioned by echonax, you should use the complete url, with http included:
private loggerUrl = 'http://localhost:3039/read/getall/'

Resources