【问题标题】:Angular front end not getting appropriate response for http request from express backendAngular 前端没有从快速后端获得对 http 请求的适当响应
【发布时间】:2019-05-07 19:39:29
【问题描述】:

我正在使用 Angular 7 向 Express 4 后端代码发送 http 请求,但不断收到 404 响应作为回报。我认为这可能是我列出http请求路径的方式的问题,但不确定。这是我第一次尝试这样的事情。我在 Angular 中设置了一个 proxy.conf.js 文件以允许跨源通信(角度在 localhost:4200 上运行,在 localhost:8085 上运行)。我的 Express 代码保存在 C:/ABC/myapp 下。以下是相关代码:

Angular proxy.conf.js 文件:

{
  "/": {
    "target": "http://localhost:8085",
    "secure": false,
    "logLevel": "debug"
  }
}

发送 http 请求的 Angular 服务代码:

export class ContactUsService {
private url = '/contactus';
private result: any;
message: string;

addMessage(contactUsMessage: contactUsInterface): Observable<contactUsInterface> {
  return this.http.post<contactUsInterface>(this.url, contactUsMessage). (retry(3));
};

constructor(private http: HttpClient) {}
};

表达 app.js 代码:

var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var createError = require('http-errors');
var express = require('express');
var logger = require('morgan');
var mongoose = require('mongoose');
var path = require('path');
var winston = require('winston');
var contactUsRouter = require(path.join(__dirname, 'routes', 'contactUs'));
var app = express();

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/contactus', contactUsRouter);

app.use(function(req, res, next) {
  next(createError(404));
});
app.use(function(err, req, res, next) {
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;

contactUs.js 代码(用于contactUsRouter):

var express = require('express');
var router = express.Router();
var contactUsMessage = require('../models/contactUsMessage');

  router.route('/contactus')
    .get(function(req,res,next){
      res.send("Hello")
    })
    .put(function(req,res,next){
      res.send("Hello")
    });

module.exports = router;

当我到达contactus页面(url:localhost:4200/contactus)并执行表单的提交按钮时,我收到以下错误: 在浏览器控制台中:“HTTP404:未找到 - 服务器未找到与请求的 URI(统一资源标识符)匹配的任何内容。 (XHR)POST - http://localhost:4200/contactus"

在 npm 日志中:“POST /contactus 404 3.081 ms - 2128 错误:无法在视图目录“C:\ABC\myapp\views”中查找视图“错误”。

关于我做错了什么有什么智慧的话?

【问题讨论】:

  • 你好像没有在contactUs.js中定义POST方法
  • 你能用像 Postman 这样的 Rest 工具来访问 Api 吗?
  • 目前你有一个 POST 路由暴露在/contactus/contactus。这是因为/contactus 的基本路由是通过app.use('/contactus', contactUsRouter); 指定的。然后你再次用/contactus 定义POST。

标签: node.js angular express


【解决方案1】:

目前您正在公开POST /contactus/contactus 的路由,因为您使用语句app.use('/contactus', contactUsRouter); 指定基本路由,然后添加/附加一个附加/额外/contactus 并注册POST/PUT 路由。

尝试将 POST 路由更改为 '/'

var express = require('express');
var router = express.Router();
var contactUsMessage = require('../models/contactUsMessage');

  router.route('/')
    .get(function(req,res,next){
      res.send("Hello")
    })
    .post(function(req,res,next){
      res.send("Hello")
    });

module.exports = router;

希望对您有所帮助!

【讨论】:

  • 糟糕,我的意思是写“post”而不是“put”。这似乎至少解决了我询问的错误。现在我在 npm 日志中收到此错误:“GET /contactus 500”。并且浏览器控制台给出了这个错误:“HTTP500: SERVER ERROR - 服务器遇到了阻止它完成请求的意外情况。GET - localhost:4200/contactus”。此外,即使 Angular 应用程序没有发出 get 请求, router.route 是否会根据 get 请求采取行动?当我第一次检索 website.com/contactus 时,节点日志显示:“[HPM] GET /contactus -> localhost:8085”。
  • 导航到website.com/contactus,即使没有HttpClient.get(),也会触发快递GET /contactus来触发。正如另一个答案中提到的,建议将 API 路由放在某种基础/前缀下,例如 /api/ 以避免产生这样的冲突。
  • 您能否详细说明这一点?使用 /api/ 如何避免这样的冲突?为此,我是否必须更改 Angular 应用程序中的所有路径以包含“/api/”,以便传递给 http 请求的 url 类似于“/api/contactus”?
  • 是的,您将在 express 应用程序中更新所有 REST API 路由以使用 /api 前缀,并更新 Angular 中的所有请求以将 /api 前缀用于任何 HttpClient 请求。通常你会添加包罗万象的逻辑来表达加载(sendFile())你的 Angular 的 index.html 任何 API 端点都没有被命中/匹配。
  • 谢谢。避免这些类型的冲突的“/api”是什么?我假设这个带有 sendFile() 的包罗万象的逻辑将在 app.js 的错误处理程序中,还是我必须将它包含在 express 应用程序的每个路由器代码中?
【解决方案2】:

您的代理配置文件无法正常工作。

请求仍在尝试在端口 4200 上运行的角度应用程序中寻找 POST 方法路由 /contactus ((XHR)POST - http://localhost:4200/contactus)不存在,因此你得到一个 404。

确保您已按照官方 Angular 网站上提到的步骤 - Add Proxy for backend server - angular.io

建议您使用代理路径 /api 而不是 / 。像这样的

{
  "/api": {
    "target": "http://localhost:8085",
    "secure": false
  }
}

希望对你有帮助

【讨论】:

  • 实际上,这是我一直难以理解的一件事。 url中没有“/api”,为什么还要在proxy.conf文件中使用“/api”?
  • 唯一的目的是从您可能希望将请求发送到另一个后端服务器的角度来看。如果您在端口 8086 上有另一台后端服务器,您可能希望向该服务器发送一些请求,其中一些向端口 8085 发送。使用 /api 类型的标识符可能有助于区分以处理此类情况。
猜你喜欢
  • 2016-07-10
  • 1970-01-01
  • 2022-08-19
  • 2021-08-20
  • 2021-08-15
  • 2021-01-06
  • 2018-11-25
  • 1970-01-01
  • 2017-06-22
相关资源
最近更新 更多