vue axios 配置上服务器后报错'Access-Control-Allow-Origin' header](亲测)
vue項目配置到服務器后,請求能夠成功,返回的數據也能在瀏覽器中看見,但是報錯:
Failed to load?http://pre.api.jmxy.mockuai.c...: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. Origin 'http://pre.promotion.jmxy.moc...' is therefore not allowed access. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
請求狀態碼為200. 在瀏覽器中也能看到返回的數據:
下面是requestheader 和 response headers
我配置的axios為:
var instance = axios.create({baseURL: baseUrl,timeout: 1000 * 12, // 創建axios實例,設定超時時間是12swithCredentials: true, // 允許攜帶cookieheaders: {"Content-Type": "application/x-www-form-urlencoded;charset=utf-8"} });我用的vue 3.0-cli ,然后新建了一個vue.config.js 文件,里面代理設置如下:
devServer: {open: true,host: "0.0.0.0", //本地真機測試// host: "localhost",port: 8900,https: false,hotOnly: false,disableHostCheck: true,proxy: {"/api/": {target: "http://pre.api.jmxy.mockua.com/",secure: false,pathRewrite: {"^/api/": ""},changeOrigin: true,logLevel: "debug"}}}但是部署到服務器后,發現請求并不會轉發到target的地址,而是直接請求到配置的服務器地址:
http://pre.promotion.jmxy.moc...?,
但是實際接口地址是:http://pre.api.jmxy.mockua.com/
搜了一圈下來都是說要后端那邊配置Access-Control-Allow-Origin為我請求的這個域名,但是后端嘗試配置了一下,發現問題并沒有解決,而且指定了域名后,這個服務器的其他幾個項目就不能正常訪問了。 所以想請問下這個問題前端有沒有解決的辦法,或者后端的解決辦法,謝謝各位!
已解決:
解決方法:
withCredentials:?false,?// 允許攜帶cookie在axios里把這一條設置為false就行了,我們的項目是不需要攜帶cookie的,所以之前的項目后端都沒有改過,我剛接手,所以不太清楚,才鬧出這個問題,如果需要攜帶cookie的話,我搜了一圈下來,基本上都和下面幾位的回答的是一樣的,需要后端配置。
來源:https://segmentfault.com/q/1010000016904795/a-1020000016904951
總結
以上是生活随笔為你收集整理的vue axios 配置上服务器后报错'Access-Control-Allow-Origin' header](亲测)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: ajax 设置Access-Contro
- 下一篇: 汇款名字错了多久退回