node.js - 当调用 Axios GET 并且 express 服务器发送 .json() 时

在我的客户端 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/

相关文章:

javascript - 在 Angular 6 中处理来自第三方 URL 的发布响应。无法发布错误

c# - EF Core - 无法添加具有相同相关对象的实体

python - 如何使用分类变量和数值变量绘制相关矩阵/热图

javascript - 如何在 Google TimeLine 图表中仅在一行中设置一个条形图(带

google-cloud-functions - Firebase 日志错误 FAILED_PREC

python-3.x - 属性错误 : 'NoneType' object has no attri

python - 导入 pycurl : Library not loaded: @rpath/li

javascript - 我可以使用 jQuery globaleval 而不是 eval 来逃避内

caching - Shopify 缓存 - 哪些操作导致清除缓存

typescript - VS代码/w。在 TypeScript Monorepo 中更漂亮