問題描述
現在 web 開發都是前后端分離的年代,前后端分離的好處我就不啰嗦了,進入問題 ==>>>
使用 nuxt.js 本地開發 Vue 項目時,ajax 請求時可能會遇到跨域問題,控制台具體報錯形式如下:
Failed to load http://example.com/api/somethings.do: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.
這就是因為跨域問題導致的結果。
於是鄙人寫了一個解決 nuxtjs 本地開發跨域問題的 npm 包,具體安裝及其使用方式如下:
Nuxt.js Proxy Module
參考資料請看 nuxtjs api,
nodejs 中間件 http-proxy-middleware api
使用步驟:
一、 安裝 @gauseen/nuxt-proxy 依賴資源
npm install --save-dev @gauseen/nuxt-proxy
二、 添加 @gauseen/nuxt-proxy 資源至 nuxt.config.js 文件的 modules 對象之下
舉個栗子:
// nuxt.config.js
modules: [
// 請求代理配置,解決跨域
'@gauseen/nuxt-proxy',
],
proxyTable: {
'/api': { target: 'http://example.com', ws: false }
},
注:
/api ———————— 每個接口特定標識字段 [String]
target —————— 目標代理服務 [String]
ws —————————— 是否支持 websocket 代理 [Boolean]
歡迎訪問我的個人博客 攻城獅傳送門
未經作者允許,禁止轉載,謝謝!
歡迎留言、評論!
