【问题标题】:How to create a route in express and receive a response (`Cannot GET/api/example')?如何在 express 中创建路由并接收响应(`Cannot GET/api/example')?
【发布时间】:2020-03-30 23:55:19
【问题描述】:

当我尝试引用 http://localhost: 8000/api/example 时,我在 Postman 中收到消息 Cannot GET/api/example(未找到 404)。我的目标是收到回复消息:

{
   data: 'You hit example endpoint'
} 

在 Postman 中我设置为 headers Content-Type: application/json


const express = require('express');

const app = express();

app.get('api/example', (req, res) => {
    res.json({
        data: 'You hit data endpoint'
    });
});

const port = process.env.port || 8000;

app.listen(port, () => {
    console.log(`connect on the port ${port}`);
});

【问题讨论】:

  • 在您的路线上添加前导斜杠并将app.get('api/example', ...)更改为app.get('/api/example', ...)

标签: javascript node.js express postman


【解决方案1】:
app.get('api/example', (req, res) => {

您请求的是/api/example 而不是api/example。您需要在路由的开头指定/


在邮递员中我设置了标题Content-Type: application/json

您正在发出 GET 请求。没有描述类型的请求正文。

不要将Content-Type 请求标头与Content-Type 响应标头或Accept 请求标头混淆。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-24
    • 2015-07-05
    • 2014-07-13
    • 2019-06-10
    • 1970-01-01
    • 2021-11-07
    相关资源
    最近更新 更多