Javascript 获取api请求后返回的对象不';I don’我没有按预期工作
我正在获取一个API,它工作得很好。 但是在这种情况下,resp总是null。 我想知道如何影响对resp var的此post请求的结果Javascript 获取api请求后返回的对象不';I don’我没有按预期工作,javascript,json,fetch,Javascript,Json,Fetch,我正在获取一个API,它工作得很好。 但是在这种情况下,resp总是null。 我想知道如何影响对resp var的此post请求的结果 var resp = null fetch('http://a1a239a6.ngrok.io/api/login', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: "email="
var resp = null
fetch('http://a1a239a6.ngrok.io/api/login', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: "email=" + email + "&password=" + password,
}).then((response) => response.json())
.then((responseJson) => resp = responseJson)
.catch((error) => console.error(error))
if (resp != null) {
navigate('Welcome', {
user: resp
})
console.log(resp)
}
我认为这是因为带有导航函数的指令是在api应答之前执行的(异步)
您需要在then语句中移动它:)如果要将数据绑定到变量,应该使用提供的回调
fetch('http://a1a239a6.ngrok.io/api/login', {
method: 'POST'
}).then(function(response) {
navigate('Welcome', { user: response})
}).catch(function(err) {
// Error
});
因此,一旦成功,它将自动运行导航功能,但您可能希望在此之前验证检索到的数据
出现错误时,您可以立即运行模式或执行所需的操作
您以前的代码的问题是它无论如何都会异步运行,所以即使在回调中您将resp设置为检索到的数据,逻辑也会运行并检查null变量
fetch('http://a1a239a6.ngrok.io/api/login', {
method: 'POST'
}).then(function(response) {
navigate('Welcome', { user: response})
}).catch(function(err) {
// Error
});