无法获取到Node js和Express.js中的路由

时间:2019-03-06 18:01:05

标签: node.js express

我正在学习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}`);
});

1 个答案:

答案 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}`);
});