vue
getInitData:获取数据,回显
handleSubmit:提交数据
getInitData() {
fetch('http://localhost:4000/')
.then((res) => {
return res.json()
})
.then((data) => {
console.log(data)//获取到数据
})
},
handleSubmit() {
fetch('http://localhost:4000/post', {
method: 'POST',
headers: { //Fetch传参时需要设置headers,服务端才能接收
'Content-Type': 'application/json',
},
body: JSON.stringify(data), //data是要提交的数据
})
.then((res) => {
console.log(res)
return res.json()
})
.then((data) => {
console.log(data)
})
})
},
koa
两个接口:
get: http://localhost:4000/
post: http://localhost:4000/post
const Koa = require('koa')
const router = require('koa-router')() //注意:引入的方式
const bodyParser = require('koa-bodyparser')
const app = new Koa()
app.use(bodyParser())
//路由使用
let data = {
customT: 'https://img.syt5.com/2019/0912/20190912111829683.jpg.420.240.jpg',
input1: 'fur',
}
router.get('/', async (ctx, next) => {
ctx.body = data
await next()
})
router.post('/post', async (ctx, next) => {
data = ctx.request.body
ctx.body = {
reponse: 'ok',
}
await next()
})
//跨域配置
app.use(async (ctx, next) => {
ctx.set('Access-Control-Allow-Origin', '*')
ctx.set('Access-Control-Allow-Methods', 'GET,POST,PUT,DELETE,OPTIONS')
ctx.set('Access-Control-Allow-Credentials', true)
ctx.set(
'Access-Control-Allow-Headers',
'Origin, X-Requested-With, Content-Type, Accept, Authorization',
)
await next()
})
app.use(router.routes()).use(router.allowedMethods()) //作用:启动路由
app.listen(4000, () => {
console.log('starting at port 4000')
})