問題一:項目A通過Ajax訪問項目B的接口,獲取json數據,項目B采用Node+Express技術棧。項目A可能遇到跨域訪問控制問題。
問題二:vue-resource 能夠跨域,一般使用jsonp,但是當需要發送大量的參數到服務器的時候,需要使用post請求.本文講述跨域post請求,
問題三:報錯如下:XMLHttpRequest cannot load http://localhost:7777/login. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access.
解決方法:
服務器后端需要設置 Access-Control-Allow-Origin 為 *
解決代碼如下:
var express = require('express'); var app = express(); //設置跨域訪問 app.all('*', function(req, res, next) { res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "X-Requested-With"); res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS"); res.header("X-Powered-By",' 3.2.1') res.header("Content-Type", "application/json;charset=utf-8"); next(); }); app.use('/', index); app.listen(3000); console.log('Listening on port 3000...');
Access-Control-Allow-Origin
瀏覽器的確發出了請求,只有當目標頁面的response中,包含了 Access-Control-Allow-Origin 這個header,並且它的值里有我們自己的域名時,瀏覽器才允許我們拿到它頁面的數據進行下一步處理。
前端Vue頁面設置:
一定要設置 {emulateJSON: true},不然跨域不成功.
如果Web服務器無法處理編碼為application/json的請求,你可以啟用emulateJSON選項。啟用該選項后,請求會以application/x-www-form-urlencoded作為MIME type,就像普通的HTML表單一樣
this.$http.post('http://localhost:7777/login',data,{emulateJSON:true}).then(res => { console.log(res.status,res.statusText); alert("success"); },res=>{ console.log('error'); alert('error') } )