简体   繁体   English

在路由上使用不同方法(PUT / POST)来表达中间件

[英]Express middleware with different methods (PUT/POST) on a route

app.route('/ad/apply')
        .put(adController.applyAd)
        .post(notificationController.addNotification)

Above route won't work, I got error 404 not found if I added in 3rd line like that. 上面的路线不起作用,如果我在第3行中添加了这样的代码,则找不到404错误。 How do I do PUT and then POST? 我该先执行PUT然后执行POST吗? if it's both PUT I can just do 如果都是PUT,我可以做

app.route('/ad/apply')
        .put(adController.applyAd, notificationController.addNotification)

Above route won't work, I got error 404 not found if I added in 3rd line like that. 上面的路线不起作用,如果我在第3行中添加了这样的代码,则找不到404错误。

To reproduce your scenario locally, I tried the following code. 为了在本地重现您的方案,我尝试了以下代码。 It didnt have any specific issues with line alignment. 它与线对齐没有任何特定的问题。

'use strict';

let http = require('http');
let express = require('express');

let app = express();

let server = http.createServer(app);

const PORT = 8888;
server.listen(PORT, () => {
  console.log(`Server is up at ${PORT}`);

  app.route('/').put((req, res) => {
    return res.status(200).send({
      msg: 'hello from PUT'
    });
  }).post((req, res) => {
    return res.status(200).send({
      msg: 'hello from POST'
    });
  });

});

May be, 404 is because of some other routes taking precedence over this based on the order of declaration. 可能是404是因为其他一些路由基于声明的顺序优先于此。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM