我正在学习Node.js和Express.js。
我试图制作一个返回JSON对象的简单API,但是当访问URL localhost:4000/api/books
时,我收到消息:无法获取/ api / books 。
const express = require('express');
const app = express();
const bookRouter = express.Router();
const port = process.env.PORT || 3500;
bookRouter.route('/books');
bookRouter.get((res, req) =>{
const response = {Title: 'This is my API', Author: 'XXXX'};
res.json(response);
});
app.use('/api',bookRouter);
app.listen(port, () => {
console.log(`Running on port ${port}`);
});
答案 0 :(得分:1)
尝试一下:
const express = require('express');
const app = express();
const bookRouter = express.Router();
const port = process.env.PORT || 3500;
bookRouter.get('/books', (res, req) =>{
const response = {Title: 'This is my API', Author: 'XXXX'};
res.json(response);
});
app.use('/api',bookRouter);
app.listen(port, () => {
console.log(`Running on port ${port}`);
});