React JS Fetch Returns 空响应但 Postman 没有
React JS Fetch Returns Empty Response but Postman Does Not
我有一个 React JS 应用程序正在尝试登录基于令牌的 API(我也在开发,使用 Laravel 5.5 和 Laravel Passport)。我正在尝试实现基本登录(使用用户名和密码登录,验证后从服务器接收令牌,使用该令牌进行未来查询)。
我用来获取的代码如下:
function loginApi(username, password) {
return fetch(loginUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
grant_type: 'password',
client_id: clientId,
client_secret: clientSecret,
username: username,
password: password
})
}).then(handleApiErrors)
.then(response => response.json)
}
值得注意的是,它还没有完全完整,因为我目前只是想确定我得到的回复。
我已经解决了遇到的正常问题,例如 CORS 问题,但是我现在遇到的问题是 API 的响应只是……空的。即使在 Chrome 开发人员工具的网络选项卡中,如果我直接检查请求,响应也是空的。
但是,如果我使用 Postman 进行完全相同的相同查询,结果正是我所期望的。
这可能是什么问题?为什么完全相同的查询会 return 不同的结果?
.json 是函数,需要调用。试试..
.then(response => response.json())
您目前正在返回 .json 解析函数。
我已经成功修复它了:
client-side(使用 React 和 Fetch-API)
const update = async (credentials, productData) => {
try {
let response = await fetch('/api/products/', {
method: 'PUT',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + credentials.t
},
body: productData
})
return await response.json()
} catch (err) {
console.log(err)
}
}
server-side (Nodejs, Express with ):
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cors())
...
我有一个 React JS 应用程序正在尝试登录基于令牌的 API(我也在开发,使用 Laravel 5.5 和 Laravel Passport)。我正在尝试实现基本登录(使用用户名和密码登录,验证后从服务器接收令牌,使用该令牌进行未来查询)。
我用来获取的代码如下:
function loginApi(username, password) {
return fetch(loginUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
grant_type: 'password',
client_id: clientId,
client_secret: clientSecret,
username: username,
password: password
})
}).then(handleApiErrors)
.then(response => response.json)
}
值得注意的是,它还没有完全完整,因为我目前只是想确定我得到的回复。
我已经解决了遇到的正常问题,例如 CORS 问题,但是我现在遇到的问题是 API 的响应只是……空的。即使在 Chrome 开发人员工具的网络选项卡中,如果我直接检查请求,响应也是空的。
但是,如果我使用 Postman 进行完全相同的相同查询,结果正是我所期望的。
这可能是什么问题?为什么完全相同的查询会 return 不同的结果?
.json 是函数,需要调用。试试..
.then(response => response.json())
您目前正在返回 .json 解析函数。
我已经成功修复它了:
client-side(使用 React 和 Fetch-API)
const update = async (credentials, productData) => {
try {
let response = await fetch('/api/products/', {
method: 'PUT',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + credentials.t
},
body: productData
})
return await response.json()
} catch (err) {
console.log(err)
}
}
server-side (Nodejs, Express with ):
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cors())
...