最近在研究
nodejs
,php
的先後端分離相關東西,在調用接口的時候碰到一些跨域的問題,通過一段時間的摸索,總結出來的一些東西php
php
採用的是yii
框架,登陸的機制或者調用接口都須要前端傳遞cookie
進去,可是nodejs
的axios
接口等默認是不會傳遞cookie
的前端
搭建一個和前端處於同一域名下的代理服務器,代理服務器把前端的請求轉發到真正的目標服務器,接收到的請求再轉發給前端
這個通常都是在nginx
,apache
,iis
裏面進行轉發的node
若是不配置代理服務器的話,那應該配置目標服務器的跨域配置了,若是是二次請求(第一次預請求
OPTIONS
方法,第二次真正請求GET/POST/PUT/DELETE
)那應該配置nginx
和後端(PHP/JAVA
)代碼響應了ios
### nginx 配置 location / { if ($request_method = 'OPTIONS') { add_header Access-Control-Allow-Origin http://xc.com:9599; add_header Access-Control-Allow-Headers *; add_header Access-Control-Allow-Methods POST,OPTIONS; add_header Access-Control-Allow-Credentials true; return 204; } index test.php ; autoindex on; try_files $uri $uri/ /test.php?$args; }
//php配置 在返回的header裏面添加相應頭部 header('Access-Control-Allow-Origin:http://frontend.com:9599');//允許跨域的前端站點 header('Access-Control-Allow-Headers:*');//允許傳遞的header header('Access-Control-Allow-Credentials:true');//須要校驗 配置此項結合NODEJS的配置項能夠經過接口傳遞cookie
//nodejs 配置 const service = axios.create({ baseURL: process.env.BASE_API, // api 的 base_url timeout: 5000, // 請求超時時間 withCredentials: true // 容許攜帶cookie })
cookie
訪問問題,配置Credentials
是爲了便於接口傳遞cookie
,若是接口不用cookie
能夠不用配置此選項