后台
const koaBody = require('koa-body') //使得可以通过ctx.request.body获取用户传给后台的值
var cors = require('koa-cors'); //解决跨域问题
const sha1 = require('sha1') //连接apiCloud数据库所必须的模块
const axios = require('axios')
const Koa = require('koa')
const Router = require('koa-router')
const app = new Koa()
app.use(cors())
const db = {
appId: 'A6080003742490',
appKey: '3122A704-87DA-D8FE-ADB7-32F13576097B'
}
const request = axios.create({
baseURL: 'https://d.apicloud.com/mcm/api'
})
const apiRouter = new Router({ prefix: '/api' })
const userRouter = new Router({ prefix: '/user' })
const getHeaders = () => {
const now = Date.now()
return {
'X-APICloud-AppId': db.appId,
'X-APICloud-AppKey': `${sha1(`${db.appId}UZ${db.appKey}UZ${now}`)}.${now}`
}
}
userRouter.post('/todo', async (ctx) => {
const todo = ctx.request.body
const result = await request.post(
'todo',
todo,
{ headers: getHeaders() }
)
ctx.body = todo
})
apiRouter
.get('/todos', async (ctx) => {
const todos = await request.get('todo', {
headers: getHeaders()
}) //这里必须用异步操作
ctx.body = todos.data
})
app.use(koaBody())
app.use(userRouter.routes()).use(userRouter.allowedMethods())
app.use(apiRouter.routes()).use(apiRouter.allowedMethods())
app.listen(3333, function() {
console.log('server now listening at port 3333');
});
复制代码
前端
function getFun() {
$.ajax({
url: 'http://localhost:3333/api/todos',
type: 'get',
success: function (data) {
console.log("get结果", data);
},
error: function (error) {
console.log('Error: ' + error);
}
});
}
function postFun() {
$.ajax({
url: 'http://localhost:3333/user/todo',
type: 'post',
data:{
content:"999999999999999999",
completed:true
},
success: function (data) {
console.log("post结果", data);
},
error: function (error) {
console.log('Error: ' + error);
},
});
}
复制代码