使用nestjs和vue制作了项目,发布时遇到的问题
1、因为vue是使用的devServer的proxy,识别了 "/api",但正式地址devServer的配置是不生效的,所以需要后台也统一添加"/api",前端axio配置正式地址的请求路径
2、因为使用了session,前端需要开启 axios.defaults.withCredentials = true ,后端需要跨域,并且注意两个域名必须一致才能传递cookie,端口号可以不一致,后台需要将 Access-Control-Allow-Origin 设置为 前端的网址,不能再使用 ’*‘, Access-Control-Allow-Credentials 设为 true;
(如何不使用session,nest仅开启跨域即可)
// vue 的 vue.config.js
devServer: {
port: 6060, // 修改端口号
proxy: {
'/api': {
//服务接口地址
target: process.env.VUE_APP_URL,
ws: true,
/*pathRewrite: {
'^/api': '/'
}*/
}
}
},
// vue 的 axios的配置文件
import axios from 'axios'
// 跨域设置cookie
axios.defaults.withCredentials = true
const api = axios.create({
timeout: 20 * 1000,
});
// request 拦截器
// 可以自请求发送前对请求做一些处理
// 比如统一加token,对请求参数统一加密
api.interceptors.request.use(config => {
config.headers['Content-Type'] = 'application/json;charset=utf-8';
// 正式环境配置请求路径
if(process.env.NODE_ENV === 'production') {
config.baseURL = process.env.VUE_APP_URL
}
// config.headers['token'] = user.token; // 设置请求头
return config
}, error => {
return Promise.reject(error)
});
// nest 的 main.js
// 添加接口前缀
app.setGlobalPrefix('api');
// 开启跨域,使用session需要配置具体网址,且前后端要域名一致
// 不使用session就什么都不用配置,不用传参
app.enableCors({
origin: 'http://192.168.10.51:6061',
credentials: true,
});
3、发布打包时,因为配置了环境变量,直接运行打包后的dist/src/main.js一直都是的走的测试环境,打包时使用正式环境打包也没用,所以还是将整个项目放置到服务器后,配置了pm2的运行文件进行了启动,配置ecosystem.config.js文件启动即可,nuxt的项目也是配置这样的启动文件使用npm启动
// ecosystem.config.js
module.exports = {
apps: [
{
name: 'snow',
exec_mode: 'fork', // 单进程
// exec_mode: 'cluster', // 集群模式,
port: '3000',
instances: '1', // Or a number of instances max 会使用服务器内核数启动相应进程
script: '/www/server/nvm/versions/node/v16.13.0/bin/npm',
args: 'run start',
},
],
};