javascript - 如何在 Express 中创建路线并接收响应 (`Cannot GET/api/example' )?

标签 javascript node.js express postman

当我尝试引用 http://localhost:8000/api/example 时,我在 Postman 中收到消息 Cannot GET/api/example (Not Found 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', (req, res) => {

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

<小时/>

In Postman I set in headers Content-Type: application/json

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

请勿将 Content-Type 请求 header 与 Content-Type 响应 header 或 Accept 请求 header 混淆。

关于javascript - 如何在 Express 中创建路线并接收响应 (`Cannot GET/api/example' )?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60934409/

相关文章:

javascript - 提交表单后 req 为空 jade

javascript - 如何使用 Node Express 从嵌套路由重定向到顶级路由?

javascript - 使用类属性时 jQuery 选择下一个子元素

javascript - 防止 VueJS 中的滚动

javascript - 扩展对象的类方法 - 正确的方法

node.js - 安装 grunt - 是否安装?

node.js - 向 Error 对象添加属性时出现 Typescript 错误 "Property ... does not exist on type ' Error'"

javascript - 根据来自另一个具有相同长度的数组的值过滤数组

node.js - Node knex Bookshelf - 使用带 fetch 的动态 where 子句

node.js - 如何以express方式发送缓冲区数据?