express 中的 app.js
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var phonesRouter = require('./routes/phones');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({extended: false}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
/* 跨域代碼 */
app.use((req, res, next) => {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE,OPTIONS");
res.header("Access-Control-Allow-Headers", "Content-Type");
next();
});
app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/phones', phonesRouter);
// catch 404 and forward to error handler
app.use(function (req, res, next) {
next(createError(404));
});
// error handler
app.use(function (err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
express ./routes/phones.js
var express = require('express');
var router = express.Router();
let phones=[
{id:1,name:'iphone'},
{id:2,name:'xiaomi'},
{id:3,name:'huawei'}
]
router.get('/', function(req, res, next) {
res.json(phones);
});
module.exports = router;
vue的 PhoneSeller.vue代碼
<template>
<div>
<div id="seller">
<form action="#" @submit.prevent="addPhone">
<input type="text" ref="pname">
<input type="submit">
</form>
<table>
<caption><h5>手機銷售排行</h5></caption>
<tr :key="phone.id" v-for="phone of phones">
<td>{{phone.id}}</td>
<td>{{phone.name}}</td>
<td><button @click="deletePhone(phone.id)">刪除</button></td>
</tr>
</table>
</div>
</div>
</template>
<script>
export default {
name: "PhoneSeller",
data:function () {
return {
maxid:2,
phones:[]
}
},
mounted:function(){
fetch('http://localhost:3000/phones',{
method:"GET"
}).then(res=>res.json())
.then(phones=>this.phones=phones)
},
methods:{
deletePhone(id){
let index=this.phones.findIndex(phone=>phone.id==id)
this.phones.splice(index,1)
},
addPhone(){
let phoneName=this.$refs.pname.value
let phone={id:++this.maxid,name:phoneName}
this.phones.push(phone)
}
}
}
</script>
<style scoped>
#seller{
width: 500px;
margin: 0 auto;
}
table{
width: 490px;
border: 2px solid gray;
border-collapse: collapse;
}
td{
border: 1px solid gray;
}
</style>