nuxt配置代理
- 安装@nuxtjs/axios, @/nuxtjs/proxy 插件
npm i @nuxtjs/axios @/nuxtjs/proxy -S
modules: ["@nuxtjs/axios","@nuxtjs/proxy",],axios: {proxy: true,},proxy: {"/api": {target: "http://localhost:4000",pathRewrite: {"^/api": "",},},},
- 使用nodejs启动一个localhost:4000的服务,写一个接口
const http = require("node:http");
const url = require("node:url");http.createServer((req, res) => {const { pathname } = url.parse(req.url);if (pathname === "/api") {res.end("代理 4000 成功");}}).listen(4000, () => {console.log("启动4000服务");});
- 在pages中的某一个xxx.vue中使用asyncData函数调用下接口:
async asyncData({ $axios }) {let res = $axios.get("/api").then(res=>{})console.log("res222:", res);return {res,};},
- 前端启动的服务是3000,接口顺利调用成功,代表代理配置好了,解决了跨域