首页 > 解决方案 > 如何在 express 中创建路由并接收响应(`Cannot GET/api/example')?

问题描述

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

{
   data: 'You hit example endpoint'
} 

在邮递员我设置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}`);
});

标签: javascriptnode.jsexpresspostman

解决方案


app.get('api/example', (req, res) => {

你要求/api/exampleapi/example。您需要/在路线的开头指定 。


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

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

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


推荐阅读