vue+node.js使用socket.io实现对战小游戏(2)

发布于 2020-09-04  1299 次阅读


起篇

考完试后这几天先把之前的学的很差的c++学了一遍,把虚基类,虚函数那里好好学了一下,然后今天继续开始自己肝代码了,so继续开始更新,可能会写几个月吧(开学后会没时间码代码了)

过程

前端页面构建

前端的页面已经都写好了,还写了部分逻辑,同时封装了axios,以及一些ui交互问题,下面是封装的base.js


/*
 * @Author: 阡陌
 * @Date: 2020-09-04 19:52:57
 * @LastEditors: 阡陌
 * @LastEditTime: 2020-09-04 22:03:01
 * @FilePath: \gameuser\gameplayer\src\base\base.js
 */
import axios from 'axios';
let localhosts = 'http://localhost:3000';   //请求的后台域名
axios.interceptors.request.use(config => {//请求之前(可以设置token)
    if (localStorage.name) {
        config.headers['Authorization'] = localStorage.name;
        config.headers['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';
    }
    return config
}, error => {
    return Promise.reject(error);
});
axios.interceptors.response.use(response => {//数据拿到之后
    return response.data
}, error => {
    return Promise.reject(error.response);;
});
function successfun(res) {//处理后台返回的非200错误
    if (res.code === 200) {
        return res
    } else {
        return res;
    }
}
function errorfun(res) {
    if (res.code != 200) {
        return res;
    }
}
export default {
    post(url, data) {//post请求
        return axios({
            method: 'post',
            baseURL: localhosts,
            url,
            data: data,
            withCredentials: true,
            timeout: 5000,//响应时间
        }).then(res => {
            return successfun(res)
        }, err => {
            return errorfun(err);
        })
    },
    get(url, params) {//get请求
        return axios({
            method: 'get',
            baseURL: localhosts,
            url,
            params,
            withCredentials: true,
            timeout: 5000,
        }).then(res => {
            return successfun(res)
        }, err => {
            return errorfun(err)
        })
    }
}

还有一些丑丑的前端,等全写好了再发截图好了

后端处理

还是日经的跨域问题,其实在前端vue设置代理也可以,但是本质是后端的问题,所以在node服务端使用中间件处理跨域


var allowCors = function(req, res, next) {
  res.header('Access-Control-Allow-Origin', req.headers.origin);
  res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
  res.header('Access-Control-Allow-Headers', 'Content-Type');
  res.header('Access-Control-Allow-Credentials','true');
  next();
};
app.use(allowCors);//使用跨域中间件

比较崩溃的是出现了写过的代码不知道是干嘛的,以及有些处理数据我已经在前端处理了。。有点崩溃,等写到那里的时候再说,大概今天做的最多的就是把页面写好了,继续更ing~