简体   繁体   中英

Expo json Unexpected End of Input

I have a pretty simple bit of javascript that sends a post command. As expected, I get a promise from the fetch command, but when trying to use the promise with response.json() I get an Unexpected end of input Syntax Error at the line indicated below. I get no issue when using response.text() and various other methods, it just seems to be .json() that breaks stuff. I am using React Native and this same code has worked fine with Node.js.

async function postData (url, data) {
  const params = {
    mode: 'no-cors',
    method: 'POST',
    headers:{
      Accept: 'application/json',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(data)
  };
  let response = await fetch(url,params);
  var responseJson = await response.json();//This seems to be the problem
  return response;
}

Here is some more code that may be helpful.

function postStuff() {
  var url = "http://192.4.20.69:1337";
  postData(url, data)
  .then(res => {
    console.log(res);
  });
}

export default function App() {
  console.log("App Executed");
  return (
    <View style={styles.container}>
      <StatusBar style="auto" />
      <Text>Hello!!</Text>
      <Button
        title="Post"
        color={"#696969"}
        accessibilityLabel="Click to send message"
        onPress={postStuff}
      />
    </View>
  );
}

Any help figuring out why .json() is breaking this would be appreciated. I'd like to try sticking with using fetch but if I need to I can use one of the other ways of handling json but I think I may still run into the issue concerning .json() .

Probably the issue lies in the server side response. response.json() fail if no json is returned. I suggest to you to check server response by adding a try catch around response.json() and print out response.text() in the catch . It could also be due to the fact that your response is missing the required header content-type and fetch doesn't know how to parse it. So you could try yo do something like this

async function postData (url, data) {
  const params = {
    mode: 'no-cors',
    method: 'POST',
    headers:{
      Accept: 'application/json',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(data)
  };
  let response = await fetch(url,params);
  try{
     return await response.json();//This seems to be the problem
   }catch(e){
    console.error(e);
    const textResponse = await response.text();
    return JSON.parse(textResponse)
  }
  return response;
}

Also I notice that you are returning response instead of responseJson that also could be the problem here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM