[英]having a hard time sending data via PUT method. getting unrecognized token '<'
我正在尝试对我的应用程序进行更改,但我遇到了困难并不断收到错误无法识别的令牌。 我检查了我的 API
如果有人可以查看 sendData() 并让我知道是否有任何问题,我将不胜感激。
'''
handleSubmit = () => {
const {screenProps: {auth: {logInUser}}, navigation: {navigate}} = this.props
console.log("props:" + this.props)
const user = {
password: this.state.password,
email: this.state.email,
}
if (requiredFields(['email', 'password'], ['Email Address', 'Password'], this.state)) {
logInUser(user, navigate)
sendData(this.user, this.state.password, this.state.email ).then(r => console.log(r) )
async function sendData(user,password, email) {
try {
const url = (my_api_url)
const resp = await fetch(url, {
method: 'PUT',
headers: myHeaders(user),
body: JSON.stringify({EmailAddress: email, Password: password}),
})
const results = await resp.json()
this.setState({isFetching: false})
if (results.errors) {
throw new Error(result.Error)
} else {
console.log(result)
}
} catch (e) {
Alert.alert(e.title, e.message)
} finally {
}
}
这一行:
const results = await resp.json()
将尝试将 api 的结果转换为 javascript object。 如果您尝试将 html 解析为 json,您遇到的错误通常是您遇到的错误。 所以我的猜测是你的 API 没有返回 JSON 而是某种默认错误。 (404,500,...)。
要验证这一点,您可以打印出响应并检查返回的数据。
在尝试反序列化响应之前,请始终检查响应状态代码和内容类型,以便您可以优雅地处理错误和意外响应,而不是获得未处理的异常。
尝试这个:
async function sendData( user, password, email ) {
try {
const url = (my_api_url)
const resp = await fetch( url, {
method: 'PUT',
headers: myHeaders(user),
body: JSON.stringify( { EmailAddress: email, Password: password } ),
} );
if( resp.ok ) { // `resp.status >= 200 && resp.status < 299`
if( resp.headers.get("Content-Type") == "application/json" ) {
const j = await resp.json();
this.setState({isFetching: false})
gotJsonResponse( j );
return;
}
}
const body = await resp.text();
this.setState({isFetching: false})
// Gracefully handle non-Success or non-JSON responses here:
} catch (e) {
Alert.alert(e.title, e.message)
} finally {
}
}
function gotJsonResponse( responseBody ) {
if (results.errors) {
throw new Error(result.Error)
} else {
console.log(result)
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.