这应该非常简单,我采取的步骤是:
1)使用vue cli3创建vue项目(效果很好)。
2)在根级别创建一个服务器文件夹
3)创建一个index.js文件
4)创建api / routes / users.js
我进入http://localhost:4000/api/add
浏览器,无法获取api / add。
这是我的索引文件:
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 users = require('./api/routes/users');
app.use('api/add', users);
const port = process.env.PORT || 4000;
app.listen(port, () => console.log(`Listening on port ${port}...` ));
下面是我的users.js文件:
const mongodb = require('mongodb');
const router = express.Router();
router.get('/', (req, res) => {
res.send('hello');
})
module.exports = router;
这是我的包JSON的样子,不确定是否因为我先创建前端然后启动后端而以某种方式造成了问题。
{
"name": "fastpo",
"version": "0.1.0",
"private": true,
"scripts": {
"serve": "vue-cli-service serve",
"start": "node server/index.js",
"dev": "nodemon server/index.js",
"build": "vue-cli-service build",
"lint": "vue-cli-service lint"
},
"dependencies": {
"axios": "^0.18.0",
"body-parser": "^1.18.3",
"cors": "^2.8.5",
"express": "^4.16.4",
"mongoose": "^5.4.11",
"morgan": "^1.9.1",
"nodemon": "^1.18.10",
"serve-favicon": "^2.5.0",
"vue": "^2.5.22",
"vue-compose": "^0.7.1",
"vuetify": "^1.3.0"
},
"devDependencies": {
"@vue/cli-plugin-babel": "^3.4.0",
"@vue/cli-plugin-eslint": "^3.4.0",
"@vue/cli-service": "^3.4.0",
"babel-eslint": "^10.0.1",
"eslint": "^5.8.0",
"eslint-plugin-vue": "^5.0.0",
"stylus": "^0.54.5",
"stylus-loader": "^3.0.1",
"vue-cli-plugin-vuetify": "^0.4.6",
"vue-template-compiler": "^2.5.21",
"vuetify-loader": "^1.0.5"
},
"eslintConfig": {
"root": true,
"env": {
"node": true
},
"extends": [
"plugin:vue/essential",
"eslint:recommended"
],
"rules": {},
"parserOptions": {
"parser": "babel-eslint"
}
},
"postcss": {
"plugins": {
"autoprefixer": {}
}
},
"browserslist": [
"> 1%",
"last 2 versions",
"not ie <= 8"
]
}
答案 0 :(得分:0)
忘记在api
之前在此处添加“ /”:app.use('api/add', users);
应该是app.use('/api/add', users)