首先我们在vue中引入axios,
npm install axios --save
在需要用到的页面引入axios
import axios from "axios";
用axios去请求koa2的服务器(url:"http://localhost:3000/")
var self=this;
axios({
url:"http://localhost:3000/",
method:"GET",
data:null
}).then(function(res){
console.log(res.data);
}).catch(function(err){
console.log(err);
})
以上是vue的代码
以下是koa的代码
// 导入koa,和koa 1.x不同,在koa2中,我们导入的是一个class,因此用大写的Koa表示:
const Koa = require('koa2');
// 注意require('koa-router')返回的是函数:
const router = require('koa-router')();
const bodyParser = require('koa-bodyparser');//用来解析request中的body,针对post请求
const cors = require('koa-cors');//允许其它域访问!!! // 创建一个Koa对象表示web app本身:
const app = new Koa(); // log request URL:
app.use(async (ctx, next) => {
console.log(`Process ${ctx.request.method} ${ctx.request.url}...`);
ctx.response.body="哈喽";
await next();
}); router.get('/', async (ctx, next) => {
ctx.response.body = `<h1>Index</h1>
<form action="/signin" method="post">
<p>Name: <input name="name" value="koa"></p>
<p>Password: <input name="password" type="password"></p>
<p><input type="submit" value="Submit"></p>
</form>`;
}); router.post('/signin', async (ctx, next) => {
var
name = ctx.request.body.name || '',
password = ctx.request.body.password || '';
console.log(`signin with name: ${name}, password: ${password}`);
if (name === 'koa' && password === '12345') {
ctx.response.body = `<h1>Welcome, ${name}!</h1>`;
} else {
ctx.response.body = `<h1>Login failed!</h1>
<p><a href="/">Try again</a></p>`;
}
}); app.use(cors());//在创建router之前注册
//koa-bodyparser必须在router之前注册上
app.use(bodyParser());
// add router middleware:
app.use(router.routes()); // 在端口3000监听:
app.listen(3000);
console.log('app started at port 3000...');