node.js - 当调用 Axios GET 并且 express 服务器发送 .json() 时,在 xhr.js 上捕获 404

标签 node.js express xmlhttprequest axios http-status-code-404

在我的客户端 Vue.js 应用程序上,当调用我的 express API 时,控制台给我一个 404 错误,API token 无效。

例如调用 http://localhost:8081/confirmation/invalidToken 给我,我

xhr.js?b50d:172 GET http://localhost:8081/confirmation/a 404 (Not Found)

当然有人可能会使用那个无效链接,所以我想处理这些错误而不是在控制台上打印错误。

如果在我的快速服务器端,我会像这样发送响应:

return res.status(404);

然后控制台错误消失。 编辑:然而,这似乎只是这种情况,因为请求尚未完成并且正在等待。一段时间后,控制台记录“net::ERR_CONNECTION_RESET”错误。

它只有在我发送这样的响应时才会出现:

return res.status(404).send({
  message: 'No valid link!',
  error,
});

或者这个:

return res.status(404).send({
  message: 'No valid link!',
  error,
});

在客户端捕获不适用于此问题。

public async sendConfirmation(token: string): Promise<any> {
  try {
    return axios.get(this.baseURL + '/confirmation/' + token);
  } catch (error) {
  // tslint:disable-next-line:no-console
    console.log(error.response);
  }
}



sendConfirmation(this.token)
 .then((res) => {
   // tslint:disable-next-line:no-console
   console.log(res);
   if (res.status === 404) {
     throw new Error("404");
   }
   this.data = res.data;
   if (res.status === 201) {
     this. messagetype = 1;
   } else if (res.status === 200) {
     this.messagetype = 2;
   }
})
.catch((err) => {
  this.messagetype = 0;
  // tslint:disable-next-line:no-console
  // console.log(err );
});

有谁知道捕获控制台错误的方法,而不必删除服务器结果中的自定义消息?

最佳答案

我在具有变量环境的 webpack 项目中的 heroku 中有同样的错误,我将 .env 文件的路径设置为本地路径,如 c:/project/.env,因此服务器变量总是返回未定义,将路径更改为相对一个修复了错误:

    if (process.env.REACT_APP_ENV === "development") {
  require("dotenv").config({
    path: ".env.development",
  });
}

还要检查 .env 文件,确保没有引号:

SERVER_URI=https://yourApp.com

不是这个:

SERVER_URI="https://yourApp.com"

你必须稍后在 webpackconfig 中将其字符串化。

这可能会帮助某人或给他一个提示。

关于node.js - 当调用 Axios GET 并且 express 服务器发送 .json() 时,在 xhr.js 上捕获 404,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57240948/

相关文章:

node.js - GCP - Compute Engine to Storage per group/user access ACL with custom Auth system

node.js - CMD批处理文件: How to use a text file to input commands

mysql - Sequelize - afterBulkUpdate() 如果更新与否如何获取

html - 无法访问 Heroku 中的 Express 服务器

javascript - 如何判断是使用XMLHttpRequest还是XDomainRequest?

javascript - 向 Flask 提交多个表单(400 BAD REQUEST)

javascript - 循环本地 JSON 文件中的数据以 HTML 格式输出

javascript - 调整这个 RPG 战斗循环?

node.js - 使用 express-fileupload 上传文件

node.js - Node Express.js - 从内存下载文件 - 'filename must be a string'