uniapp開發H5時,基本上都會遇到跨域問題:json
下面是個完整的請求示例:api
關鍵在於header請求頭:跨域
header: {
'Access-Control-Allow-Origin': '*', //跨域加上頭
'Content-Type': 'application/x-www-form-urlencoded'
},緩存
Content-Type傳入內容格式設置爲'application/x-www-form-urlencoded'時app
數據格式爲"data":"66666"async
與'Content-Type': 'application/json'jsonp
不一樣的是json格式不帶「」--->data:6666,this
發送內容格式的不一樣:數據格式也就不一樣;url
具體內容類型參照:http://tool.oschina.net/commons.net
//登陸請求開始 let loginurl = '/betago-api/auth/login'; let isok=false; var that=this; // console.log(datas); uni.request({ url: loginurl, //登陸API地址。 data: { mobile: datas.account, password: datas.password }, method: 'POST', dataType: "jsonp", async: true, header: { 'Access-Control-Allow-Origin': '*', //跨域加上頭 'Content-Type': 'application/x-www-form-urlencoded' }, //登陸成功後返回 success: function(res) { console.log(res.data); //登陸成功後存入緩存用戶信息(必要信息) let dataInfo=JSON.parse(res.data); if (dataInfo.code=="0") { const userInfo1 = { account: datas.account, password: datas.password, headImagePath: dataInfo.data.headImagePath, coins: dataInfo.data.coins, signature: dataInfo.data.signature, userId: dataInfo.data.userId, userTypeCode: dataInfo.data.userTypeCode, testPlannedDate: dataInfo.data.testPlannedDate, fileOssUpload: dataInfo.data.fileOssUpload, LoginName: dataInfo.data.name, }; service.addUser(userInfo1); //返回登陸成功信息 isok= true; } if (isok) { that.toMain(datas.account); } else { uni.showToast({ icon: 'none', title: '用戶帳號或密碼不正確', }); } } });