WebSocket connection to 'ws:// failed:
Error during WebSocket handshake:
Unexpected response code: 400 socket.io-1.2.0.js:2
Any suggestions for this, irrespective of research I couldn't find any solution to this problem,
any idea what went wrong on this and how can it be fixed
Node.js
app.use(function(request, response, next){
response.header("Access-Control-Allow-Origin", "*");
response.header("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE");
response.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, X-Auth-Token");
next();
});
Related
I'm using Angular 8 and ExpressJS. Everything work perfectly, the app is live and a lot of users (6000) are using it. But there are a few users (less than 10) that get Unknown Error (code 0) from any API call.
This is the error response:
{"headers":{"normalizedNames":{},"lazyUpdate":null,"headers":{}},"status":0,"statusText":"Unknown Error","url":"https:/xxxxxxxxxx/api/auth/recover-pass","ok":false,"name":"HttpErrorResponse","message":"Http failure response for https://xxxxxxxx/api/auth/recover-pass: 0 Unknown Error","error":{"isTrusted":true}}
I readed it can be an CORS error, but I don't think so. I'm using this
app.use((req, res, next) => {
res.setHeader("Access-Control-Allow-Methods", "POST, PUT, OPTIONS, DELETE, GET");
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, x-access-token");
res.header("Access-Control-Allow-Credentials", true);
next();
});
I am running a server with express at port 3000 and a client with angular 7 at port 4200. Once I make a request, I run into CORS issue.
Access to XMLHttpRequest at 'http://localhost:3000/drug' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
I have tried all the solutions online like using cors package, and setting the middleware before router like below codes (Angular 6 - No 'Access-Control-Allow-Origin' header is present on the requested resource). But it still is not solved and keep getting same errors. Does anyone have same problem that CORS is not solved with all the solutions? Could you please help me?
app.use((req, res, next) => {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT");
res.header(
"Access-Control-Allow-Header",
"Origin, X-Requested-With, Content-Type, Accept"
);
next();
});
app.use((req, res, next) => {
res.header("Access-Control-Allow-Origin", "http://localhost:4200");
res.header("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT");
res.header(
"Access-Control-Allow-Header",
"Origin, X-Requested-With, Content-Type, Accept"
);
next();
});
Put this line of code app.use(cors()); before routing code. (Assuming you have installed cors package).
I think answer would be so late, but for somebody in future:
You have to turn it on at the server side.
I'm .Net developer, therefore I'll show in example of .Net core app.
In startup file method ConfigureServices you should add next code
services.AddCors(options =>
{
options.AddPolicy("CorsPolicy",
builder => builder.WithOrigins("http://localhost:4200")
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials());
});
After that you should edit method Configure. Add next line before calling UseMvc
app.UseCors("CorsPolicy");
That's all. I hope this answer will help to somebody.
While reading some tutorial I found that
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header('Access-Control-Allow-Methods', 'DELETE, PUT');
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
What does every res.header mean? and what are their functions?
These headers allow cross-domain access: https://ru.wikipedia.org/wiki/Cross-origin_resource_sharing
Without these headers client scripts are allowed to get data from your server (edited: in your case you specify request types DELETE and PUT) only if their origin is the same (i.e. your client-side html and javascript are loaded from the same domain name). Scripts from different domains will receive an error like 'this origin is not allowed' or something like that.
EDIT: Kevin B answered my question in a comment below. I added some logic to send a 200 request if an OPTIONS http request hit my API to fix the problem. Here is the code:
var allowCrossDomain = function(req, res, next) {
if ('OPTIONS' == req.method) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,PATCH,OPTIONS');
res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With');
res.send(200);
}
else {
next();
}
};
router.use(allowCrossDomain);
Original Question:
I currently am trying to get an Ionic 2 application running on my localhost to be able to send data to an Express 4 application. It works when I send requests without an authorization header. However, once I added auth headers, my API began to throw errors. I have done my research and have tried to implement what I found here: (https://stackoverflow.com/a/15254158/5379931.
However, I am getting errors still. If I set Access-Control-Allow-Origin like this:
res.header("Access-Control-Allow-Origin", "http://localhost:8100");
I get this error:
XMLHttpRequest cannot load URL. Response to preflight request doesn't pass
access control check: The 'Access-Control-Allow-Origin' header has a value
'http://localhost:8100/' that is not equal to the supplied origin. Origin
'http://localhost:8100' is therefore not allowed access.
If I set my Access-Control-Allow-Origin header like this:
res.header("Access-Control-Allow-Origin", "http://localhost:8100/");
I get this error:
XMLHttpRequest cannot load URL. No 'Access-Control-Allow-Origin' header is
present on the requested resource. Origin 'http://localhost:8100' is
therefore not allowed access. The response had HTTP status code 400.
Here is the rest of my express 4 code that is relevant:
router.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "http://localhost:8100");
res.header("Access-Control-Allow-Headers", "Origin, Authorization, X-Requested-With, Content-Type, Accept");
res.header("Access-Control-Allow-Credentials", true);
res.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
next();
});
It looks like you forgot to respond to the options request. By not responding, it will go to your error handler and be dealt with as if it were an error.
Just send a 200 status within your .use if it is an options request so that it doesn't reach your error handler.
I am using express package of nodejs and I have written this function to send response for any generic API. Although it keeps giving error and I can't figure out why. status function sets response status so I don't know why this should happen
function ResponseHandler(response, respObj, resData) {
var resp = {
"message" : respObj.message,
"data" : resData
}
response.status(respObj.code);
response.json(resp);
}
This is because you're sending the request back with the .status(number) and then try to send the status again with .json(string). Chain your functions and only one response will be sent.
response.status(respObj.code).json(resp);
You should use the below format:
res.status(500).json({ error: 'message' });
Check the following link to know more details:
https://expressjs.com/en/api.html
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();
});