You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Express路由创建报错:访问/api/example返回404 Not Found,如何解决?

Fixing the 404 Error for Your Express Endpoint

Hey there, let's get that endpoint working properly—you're just a couple of small fixes away from getting the expected response!

The Issues in Your Code

  • Missing leading slash in the route path: Express requires route paths to start with a /; without it, the router won't match your http://localhost:8000/api/example request correctly.
  • Incorrect response text: Your current code returns 'You hit data endpoint' instead of the expected 'You hit example endpoint'.

Corrected Code

const express = require('express');
const app = express();

// Fixed: Added leading slash to the route path, and updated the response text
app.get('/api/example', (req, res) => {
  res.json({ data: 'You hit example endpoint' });
});

const port = process.env.port || 8000;
app.listen(port, () => {
  console.log(`connect on the port ${port}`);
});

How to Verify

  1. Stop your current Express server if it's running.
  2. Run the corrected code.
  3. Send a GET request to http://localhost:8000/api/example in Postman (you don't even need the Content-Type header for a GET request, though it won't hurt to leave it in).

You should now receive the expected response:

{ "data": "You hit example endpoint" }

内容的提问来源于stack exchange,提问作者Umbro

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 06:42:27