I’m using the new vUE – CLI
First, install the required plug-ins, vue-resource, JSON-server, and proxyTable.
The directory structure is shown below
Introduce vue-resource module, vue.use (vueResource) in main.js.
1. Json-server (can’t use POST request)
Next go to the webpack.dev.conf.js file in the build directory and introduce jSON-server after const portfinder = require(‘portfinder’).
/* const jsonServer = require('json-server'/* Build a server*/ const apiServer = jsonServer.create() /* Connect db.json to server*/ const apiRouter = apiserver.router ()'db.json') const middlewares = jsonServer.defaults()\ apiserver.use (apiRouter) apiserver.use (middlewares) /* Listener port */ apiServer.listen(3000,(req,res)=>{ console.log('jSON Server is running')})Copy the code
After the server is restarted, enter localhost:3000 in the address bar of the browser. If the following page is displayed, the JSON server is successfully started
Now go to the index.js file in the config folder, find proxyTable:{} in the dev configuration and configure it there
'/api':{
changeOrigin:true// demo allows cross-domain target:"http://localhost:3000"// Interface domain name pathRewrite:{'^/api':' '// Use the new path overridden, generally do not change}}Copy the code
You can now use localhost: 8080 / API/apiName request json data
Make Ajax requests in your project through the Resource plug-in
indata(){} creates the hook function:function(){
this.$http.get('/api/newsList')
.then(function(res){this.newslist = res.data // assign newsList to data,function(err){
console.log(err)
})
}
Copy the code
2. Express (can use POST request)
Create a new routes file in your project and create api.js with the following content:
const express = require('express')
const router = express.Router()
const apiData = require('.. /db.json')
router.post('/:name',(req,res)=>{
if(apiData[req.params.name]){
res.json({
'error':'0',
data:apiData[req.params.name]
})
}else{
res.send('no such a name')
}
})
module.exports = router
Copy the code
Next go to the webpack.dev.conf.js file in the build directory and introduce express after const portfinder = require(‘portfinder’) as follows:
const express = require('express')
const app = express()
const api = require('.. /routes/api.js')
app.use('/api',api)
app.listen(3000)
Copy the code
Now go to the index.js file in the config folder, find proxyTable:{} in the dev configuration and configure it there
'/api':{
changeOrigin:true// demo allows cross-domain target:"http://localhost:3000"// Interface domain name pathRewrite:{'^/api':'/api'// Use the new path overridden, generally do not change}}Copy the code
After the restart, you can post requests to access the data.