Angular http返回状态0,但我认为是404 [英] Angular http returning status 0, but I expect 404

查看:349
本文介绍了Angular http返回状态0,但我认为是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());

当我用Angular(/404{})发出请求时:

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

我得到:

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

在Chrome控制台中,我看到请求是通过OPTIONS发出的,并且确实返回了404:

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?

我读到它可能是CORS问题...我的应用程序在4200上,服务3000.在我的服务中,我位于顶部(之前没有其他功能):

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

我不认为这是COR的问题...

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

但是我不知道,是吗?

我不会得到状态为404err吗?

Shouldn't I get err with status 404?

推荐答案

显然,OPTIONS永远不会返回404,因为它会导致此错误:

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

对预检的响应具有无效的HTTP状态代码404

Response for preflight has invalid HTTP status code 404

如果是OPTIONS请求,我将标头更改为end请求,否则继续:

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

然后请求在Angular应用上返回正确的数据:

Then the request return correct data on the Angular app:

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

这篇关于Angular http返回状态0,但我认为是404的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆