1. 程式人生 > >fetch跨域實現及post傳參問題

fetch跨域實現及post傳參問題

fetch跨域有兩種方法:

1.前端jsonp跨域

2.後端設定cors跨域

首先,嘗試了jsonp跨域,可以輕鬆成功連線上豆瓣API

引入包 fetch-jsonp

try{
        const url = `https://api.douban.com/v2/book/search?q=${searchName}&count=20`;
        yield put(fetchBooks())
        const res = yield call( fetchJsonp, url )
        const data = yield res.json().then(res=>(res))
        console.log(data)
        yield put(fetchBooksSuccess(data))
        console.log('load成功')
    }catch(e){
        console.log(e);
        yield put(fetchBooksError())
    }

很棒!!  於是自己開始搭建node服務, 開始出bug了

(1)請求後端時候遇上請求有響應但是 報錯time out的bug, 參照了官網沒法解決( 後臺不支援jsonp ??? ).

(2)請求的json資料無法解析,提示語法錯誤 ???

參考了官方解釋,仍舊一頭霧水 

Caveats

1. You need to call .then(function(response) { return response.json(); }) in order to keep consistent with Fetch API.

2. Uncaught SyntaxError: Unexpected token :

 error

More than likely, you are calling a JSON api, which does not support JSONP. The difference is that JSON api responds with an object like {"data": 123} and will throw the error above when being executed as a function. On the other hand, JSONP will respond with a function wrapped object like jsonp_123132({data: 123})

.

故此暫且放棄jsonp方法~~~~~~

後臺設定cors跨域

//設定跨域

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();

});

此段程式碼加入之後 , 前臺就可以正常訪問後臺伺服器了 , 使用get方法加上url字串拼接輕鬆實現與後臺互動

接著又出現了新的問題----當使用post與後臺互動的時候, 如何實現傳參 ? 參考了網上的幾種方式 1.body:JSON.stringify(obj) 2.formData

試驗過後formData方式不可用, 第一種方法可以使用,但是要加上

"Content-type":'application/x-www-form-urlencoded'

下面貼出實現程式碼:

get:


fetchLogin(values){

    let url = 'http://localhost:8080?name='+values.username+'&password='+values.password

    fetch(url).then((res) => {

        console.log(res)

        return res.json()

    }).then((data)=>{

        console.log(data)
        
    }).catch((err) => {

        console.log(err)

    })

}

post

fetchLogin2(values){

    let url = 'http://localhost:8080/register'

    let obj = { name:values.username2,password:values.password2 }

    fetch(url,{

        method:'post',

        headers:{

            "Content-type":'application/x-www-form-urlencoded'

        },

        body:`data=${JSON.stringify(obj)}`

    }).then((res) => {

        console.log(res)

        return res.json()

    }).then((data)=>{

        console.log(data)

    }).catch((err) => {

        console.log(err)

    })

}