在前端開發過程當中,先後端聯調的時候,總會遇到各類問題,今天我簡單作一個各個狀況的總結,以便記錄和分享給你們!
若api接口已經開發完畢,這不存在這個問題,前端直接調接口便可,基本廢話😁
咱們都知道,跨域問題是瀏覽器端和服務器端纔會有的,服務端和服務端是不存在跨域問題的。 那麼前端在自測時,如何避免跨域呢? 瀏覽器---》服務器(走到這個服務器的時候,咱們可使用devServer或者nginx處理)---》API
+1)前端能夠在vue.config.js配置文件自定義接口,配置devServer(說實話,這個方法須要前端懂點node,也有點費精力)html
const bodyParser = require("body-parser"); module.exports = { devServer: { before: app => { // 設置參數處理中間件 app.use(bodyParser.json()); // post參數 // url參數 app.use( bodyParser.urlencoded({ extended: true, }), ); app.post("/dev-api/user/login", (req, res) => { const { username } = req.body; if (username === "admin" || username === "jerry") { res.json({ code: 1, data: username, }); } else { res.json({ code: 10204, message: "用戶名或密碼錯誤", }); } }); app.get("/dev-api/user/info", (req, res) => { // 請求頭獲取token const auth = req.headers["authorization"]; // 轉換爲響應的roles const roles = auth.split(" ")[1] === "admin" ? ["admin"] : ["editor"]; res.json({ code: 1, data: roles, }); }); }, } }
+2)先後端代碼分離的狀況,假如node端寫api。須要前端配置一下proxy。前端
1)在項目中建立server目錄,建立index.jsvue
const express = require("express"); const app = express(); const bodyParser = require("body-parser"); app.use(bodyParser.json()); app.use( bodyParser.urlencoded({ extended: true }) ); app.post("/user/login", (req, res) => { const { username } = req.body; if (username === "admin" || username === "jerry") { res.json({ code: 1, data: username }); } else { res.json({ code: 10204, message: "用戶名或密碼錯誤" }); } }); app.get("/user/info", (req, res) => { const roles = req.headers['authorization'].split(' ')[1] ? ["admin"] : ["editor"]; res.json({ code: 1, data: roles }); }); app.listen(3000);
2)在vue.config.js的devServer中配置代理node
proxy: { // 代理 /dev-api/user/login 到 http://127.0.0.1:3000/user/login [process.env.VUE_APP_BASE_API]: { target: `http://127.0.0.1:3000/`, changeOrigin: true, pathRewrite: {//看後臺是否有,決定是否重寫 ["^" + process.env.VUE_APP_BASE_API]: "" } } },
3)啓動server下的index,監聽3000端口,一樣能夠處理跨域nginx
node index.js
4)啓動前端項目git
npm run serve
+3)使用easy-mock模擬github
注意:easy-mock網站常常掛掉,須要咱們本身在本地搭建一下本地項目,詳細步驟以下: