服务端
const Koa = require('koa');
const Router = require('koa-router') // koa 路由中间件
const app = new Koa();
const router = new Router(); // 实例化路由
const process = require('child_process');
// 使用中间件,保证可跨域
const CORS = require('./middleware/cors.js');
const { default: axios } = require('axios');
const server = require('http').createServer(app.callback());
const io = require('socket.io')(server);
io.on('connection', (socket) => {
console.log(999);
socket.on('chat message', (msg) => {
console.log('message: '+msg);
io.emit('chat message', msg);
});
socket.on('disconnect', () => {
console.log('user disconnected');
});
});
app.use(CORS())
router.get('/',async(ctx,next)=>{
ctx.response.body = 'xxx';
})
router.post('/addUrl',async(ctx,next)=>{
//Math.random()>0.5 ? 1:-1
let url = `simple${Date.now()}https`.split('').sort(()=>Math.random()>0.5 ? 1:-1).join('');
let requestList = [];
for(let i=0;i<5;i++) {
let item = "https://docs.corp.kuaishou.com/k/home/VWWB_Ri0W5fE/fcAC24yIcuGuNxWd87dSu5BKC#";
requestList.push(item.split('').sort(()=>Math.random()>0.5?1:-1).join(''));
}
const imgList = await new Promise((resolve,reject)=>{
axios({
method:'get',
url:"http://shibe.online/api/shibes?count=3"
})
.then(res=>{
resolve(res.data);
})
})
ctx.response.body = {
url,
requestList,
imgList
};
})
router.post('/deleteUrl',async(ctx,next)=>{
ctx.response.body = 'safaf';
})
app.use(router.routes());
server.listen(3000);
console.log('running service')
客户端(这里用的是vue)
设置代理 vue.config.js
module.exports ={
devServer: {
port: 8080,
proxy: {
'/socket.io': {
// 因因为用的客户端的socket插件会带这个path
target: 'ws://127.0.0.1:3000',
ws: true, // 这一行很关键 表示是否开启 websocket
},
}
}
}
使用
import io from 'socket.io-client';
created(){
const socket = io({
reconnection: true,
forceNew: true,
transports: ['websocket'],
}); //必须要加 transports: ['websocket'],才能连接上
axios.interceptors.request.use(config=>{
//浏览器默认允许跨域请求的Content-Type 只有 text/plain multipart/form-data application/x-www-form-urlencoded
config.headers['content-type'] = "application/x-www-form-urlencoded";
return config;
})
},