天天看點

nodejs+express跨域請求總結

一,最重要的第一步。在express腳手架中下載下傳cors。(yarn add  cors)

二,在app.js檔案中添加跨源條件

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 (); console . log ( 123 ) });

三,前端相容問題。

有時候還是不行。就把前端參數配置好。和伺服器設定的響應頭參數一樣。

$ . ajax ({ type: 'post' , url: 'http://localhost:3000/swiper' , data: { bannernumber: 5 , starnumber: 0 , "Content-Type":"application/json;charset=utf-8" } }). then ( succ , err ) 最後謝謝 知乎上的 柳丁Jason Chen。當時搞了好久,才發現位元組是沒有引入cors子產品的錯誤。