首页 > 解决方案 > Cant GET/ problem with express routes an localhost

问题描述

I watched a video by traversy media on youtube and after trying copying 1 for 1 his code i still didnt have any success with the problem. the code is suppose to route the main page('/') to the page(/routes/api/posts'), can anyone find the problem with my code? my index.js code:

const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');

const app = express();

//Middleware
app.use(bodyParser.json());
app.use(cors());

const posts = require('./routes/api/posts');

app.use('/api/posts', posts);

const port = process.env.PORT || 5000;

app.listen(port, () => console.log('server started on port ' + port));

Posts.js page:

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

const router = express.Router();

//Get Posts
router.get('/', (req,res) => {
	res.send('hello');
});

//Add Post


//Delete Post

module.exports = router;

Thanks and sorry for the bad english :(

video: https://www.youtube.com/watch?v=j55fHUJqtyw

标签: node.jsexpress

解决方案


res.send('hello')只能通过 访问GET /api/posts。你应该使用:

const posts = require('./routes/api/posts');
app.use('', posts);

推荐阅读