Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular http returning status 0, but I expect 404

I'm making a request to a server that has the following routes:

app.use('/401', (req, res) => res.status(401).end());
app.use('/403', (req, res) => res.status(403).end());
app.use('/404', (req, res) => res.status(404).end());
app.use('/500', (req, res) => res.status(500).end());
app.use('/502', (req, res) => res.status(502).end());
app.use('/503', (req, res) => res.status(503).end());
app.use('/504', (req, res) => res.status(504).end());

When I make a request with Angular (/404, {}):

public async post(path: string, data: object): Promise<Response> {
  try {
    return await this.http.post(path, data).toPromise();
  } catch (err) {
    console.log('err', err);
    throw err;
  }
}

I get:

ok: false
status: 0
statusText: ""
type: 3

In Chrome console I see the request was made with OPTIONS and it did return 404:

Request URL: http://localhost:3000/404/
Request Method: OPTIONS
Status Code: 404 Not Found

Where did it go? How can I get the real error code?

I read that it could be a CORS issue... My app is on 4200 and my service 3000. In my service I have on the top (before anything else):

app.use(function(req, res, next) {
  res.setHeader("Access-Control-Allow-Origin", "*");
  res.setHeader("Access-Control-Allow-Credentials", "true");
  res.setHeader("Access-Control-Allow-Methods", "*");
  res.setHeader("Access-Control-Allow-Headers", "*");
  next();
});

I don't think it is a problem with CORs...

But I don't know, could it be?

Shouldn't I get err with status 404?

like image 697
BrunoLM Avatar asked Jul 26 '17 17:07

BrunoLM


1 Answers

Apparently OPTIONS can never return a 404 as it causes this error:

Response for preflight has invalid HTTP status code 404

I changed the headers to end the request if it is a OPTIONS request, otherwise it continues:

const headers = (req, res, next) => {
  res.setHeader("Cache-Control", "no-cache");
  res.setHeader("Access-Control-Allow-Origin", "*");
  res.setHeader("Access-Control-Allow-Credentials", "true");
  res.setHeader("Access-Control-Allow-Methods", "GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS");
  res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization, Accept");
};

app.use((req, res, next) => {
  console.log(req.method);
  headers(req, res, next);

  if (req.method === 'OPTIONS') {
    return res.end();
  }

  next();
});

Then the request return correct data on the Angular app:

ok: false
status: 404
statusText: "Not Found"
type: 2
like image 114
BrunoLM Avatar answered Oct 20 '22 11:10

BrunoLM