NodeJs 使用express在本地模拟后台服务接口
express
- 基于 Node.js 平台,快速、开放、极简的 Web 开发框架
npm init -y
npm i express cors
- 编写
server.js
文件
const express = require('express')
const cors = require('cors')
const app = express()
app.use(cors())
const hostname = '127.0.0.1'
const port = 3000
const _products = [
{ id: 1, title: 'iPad Pro', price: 500.01 },
{ id: 2, title: 'H&M T-Shirt White', price: 10.99 },
{ id: 3, title: 'Charli XCX - Sucker CD', price: 19.99 },
{ id: 4, title: 'Porsche 911', price: 18932378.22 }
]
app.use(express.json())
app.get('/products', (req, res) => {
res.status(200).json(_products)
})
app.post('/checkout', (req, res) => {
res.status(200).json({
success: Math.random() > 0.5
})
})
app.listen(port, hostname, () => {
console.log(`❗❗❗ Server is running at http://${hostname}:${port}/`)
})
- 使用
node server.js
启动服务
在Vue应用中使用
import axios from 'axios'
const state = {
products: []
}
const getters = {}
const mutations = {
setProducts(state, payload) {
state.products = payload
}
}
const actions = {
async getProducts({ commit }) {
try {
const { data } = await axios({
method: 'GET',
url: 'http://127.0.0.1:3000/products'
})
commit('setProducts', data)
} catch (err) {
// eslint-disable-next-line no-undef
$vue.$message.error(err.toString())
}
}
}
export default {
namespaced: true,
state,
getters,
actions,
mutations
}
Keep learning