处理GET路由上的POST请求(express.js)
我是新来expression和结合在一起似乎是卡住,似乎是一个简单的问题。 我有一个使用GET
的API路线。 路线:
app.get('/api/v1/all', getAllWords);
然后在getAllWords
callback函数中,我想检查发送的请求是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) } }
当我使用邮差发送一个GET
请求时,它工作得很好。 但是当发送一个POST
请求时,我得到了通用express.js“ 不能POST / api / v1 / all ”。
为什么它response.send(reply)
不工作的POST
方法?
app.get(...)
定义仅与GET方法匹配的端点。 如果你想处理POST方法,你必须在app.post(...)
提供独立的中间件app.post(...)
您可以使用app.all(...)
来处理GET
和POST
请求,但它也接受其他types的请求,如PUT
和DELETE
。 虽然我更喜欢分开GET
和POST
请求。