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 yourhttp://localhost:8000/api/examplerequest 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
- Stop your current Express server if it's running.
- Run the corrected code.
- Send a GET request to
http://localhost:8000/api/examplein Postman (you don't even need theContent-Typeheader 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
相关产品推荐
相关产品推荐

