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