代码之家  ›  专栏  ›  技术社区  ›  julanove

Express中使用和邮寄、需求和导入的区别

  •  0
  • julanove  · 技术社区  · 3 年前

    我是打字和Exress的新手。我得到了一个简单的导出函数,如下所示:

    export function testFunction(req: any, res: any)  {
    
        console.log(req.body);
    
        return res.status(200).send('OK');
        
    };
    

    一个简单的导出路径如下:

    router.post('/', async (req: any, res: any) => {
    
        console.log(req.body);
    
        return res.status(200).send('OK');
     
    });
    
    module.exports = router;
    

    这是我的服务器代码:

    import * as express from 'express';
    import {testFunction} from './rpcs/testfunction';
    var bodyParser = require('body-parser');
    var testRoute = require('./rpcs/testroute');
    
    export function initApplication() {
        const app = express();
        
        app.use(bodyParser.urlencoded({ extended: false }))
        app.use(bodyParser.json())
        app.use((req: express.Request, res: express.Response, next: express.NextFunction) => {
            res.header("Access-Control-Allow-Origin", "*");
            res.header("Access-Control-Allow-Methods", "*")
            res.header("Access-Control-Allow-Headers", "*");
            if ('OPTIONS' === req.method) {
                res.sendStatus(200);
            } else {
                next();
            }
        }) 
    
        app.get("/api/test", function (req:any, res:any) {
            res.send("Hello World!");
        });
    
        //app.post("/api/register", require("./rpcs/register"));
    
        app.post("/api/testfunction", testFunction); // Goes with fuction
    
        app.use("/api/testroute", testRoute); // Goes with Route
        
        return app;
    }
    

    它工作得很好。但当我改变时,我不明白的是

    app.use("/api/testroute", testRoute); 
    

    app.post("/api/testroute", testRoute); 
    

    错误将被发送出去。。。

    Cannot POST /api/testroute
    

    在旧的node.js项目中,我可以很好地做到这一点。但是当我将这个项目更新为打字稿时。这种错误会发生。有人能解释一下原因吗 使用 只能和 路由器 邮递 只能和 功能 ??

    0 回复  |  直到 3 年前
        1
  •  0
  •   yasnil    3 年前

    testFunction是一个处理http请求的函数。因此,动词在那里可以很好地工作,即get/post/put/patch/delete。

    testRoute不是一个函数,它是一个导入的文件,用于处理http(动词)请求。因此,本质上,您将“使用”处理动词的导入文件。实际上,您正在从这里的应用程序级处理转向路由器级处理。