gpt4 book ai didi

javascript - 处理 GET 路由上的 POST 请求 (express.js)

转载 作者:行者123 更新时间:2023-11-29 23:44:44 25 4
gpt4 key购买 nike

我是新手,无法将表达和 Node 结合在一起,似乎被一个看似简单的问题卡住了。我有一个使用 GET 的 API 路由。路线:

app.get('/api/v1/all', getAllWords);

然后在 getAllWords 回调函数中,我想检查发送的请求是 GET 还是 POST。这是我必须检查请求方法的代码:

function getAllWords(request, response) {
let reply;
if (request.method === 'GET') {
console.log('This was a GET request');
// handle GET here...
}
if (request.method === 'POST') {
console.log('This was a POST request');
reply = {
"msg": "HTTP Method not allowed"
};
response.send(reply)
}
}

当我使用 Postman 发送 GET 请求时,它工作正常。但是当发送 POST 请求时,我得到了通用的 express.js “Cannot POST/api/v1/all”。

Postman screenshot

为什么 response.send(reply) 不适用于 POST 方法?

最佳答案

app.get(...) 定义仅与 GET 方法匹配的端点。如果你想处理 POST 方法,你必须在 app.post(...)

中提供单独的中间件

关于javascript - 处理 GET 路由上的 POST 请求 (express.js),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44468174/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com