Angular http returns status 0, but I expect 404

I am 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 the Chrome console I can see that the request was made with OPTIONS

and it returned 404:

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

      

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

I read that it might be a CORS issue ... My app is at 4200 and my service is 3000. In my service I have on top (first of all):

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 this is a COR problem ...

But I don't know, do I?

Should I get err

with a status 404

?

+3


source to share


1 answer


Apparently OPTIONS

never will be able to return 404

as it throws this error:

Reply to pre-flight date has invalid HTTP 404 status code

I changed the headers to end

request if it is a request OPTIONS

, otherwise it will continue:



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();
});

      

The request then returns the correct data in the Angular app:

ok: false
status: 404
statusText: "Not Found"
type: 2

      

+2


source







All Articles