未处理的拒绝(SyntaxError)。意外的输入结束 - POST Fetch? [重复]

问题描述 投票:0回答:1

React projectPOST请求由Fetch:

getResource = async () => {
const res = await fetch('https://fanml753mfuuq-uc.a.run.app/api/v1/login/access-token', {
    headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/x-www-form-urlencoded',
        'Access-Control-Allow-Methods': 'GET, PUT, POST, DELETE, HEAD, OPTIONS'
        // 'Authorization': 'Bearer TOKEN',

    },
    method: 'POST',
    mode: 'no-cors',
    credentials: 'include',
    body: 'grant_type=&username=charl%40mavencodom&password=test&scope=&client_id=&client_secret='
});
// if (!res.ok) {
//     throw new Error(`Not Fetch, received ${res.status}`)
// }
const body = await res.json();
return body;

};

我得到 未处理的拒绝(语法错误)。意外的输入结束.如果不加评论 '如果'然后我得到 未取,收到0 .请求状态为200,但没有响应。

API文档。在这里输入图片描述

用trycatch和console.log记录错误更新代码。

 let response;
    try {
        response = await fetch(
            'https://fan-foto-ml753mfuuq-uc.a.run.app/api/v1/login/access-token',
            {
                headers: {
                    'Accept': 'application/json',
                    'Content-Type': 'application/x-www-form-urlencoded',
                    // 'Authorization': 'Bearer TOKEN',

                },
                method: 'POST',
                mode: 'no-cors',
                // credentials: 'include',
                body: 'grant_type=&username=charles%40mavencode.com&password=test&scope=&client_id=&client_secret='
            });
    } catch (error) {
        console.log(error)
        // manage errors here
    }
    console.log(response);
    return response;

** 在开发工具网络选项卡中**

请在此输入图片描述

预期结果

{
  "access_token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjo1LCJleHAiOjE1OTA1Njk4NTYsInN1YiI6ImFjY2VzcyJ9.SVnzXxc_RMfFwTuzFuK3ul-Vahej_05NpdfPqdt34EY",
  "token_type": "bearer"
}
javascript reactjs api post fetch
1个回答
-1
投票

你需要使用 trycatch 块来捕获由 fetch 调用抛出的错误(例如网络错误)。

getResource = async () => {
  let response;
  try {
    response = await fetch(
    'https://fanml753mfuuq-uc.a.run.app/api/v1/login/access-token',
    {
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/x-www-form-urlencoded',
        'Access-Control-Allow-Methods': 'GET, PUT, POST, DELETE, HEAD, OPTIONS'
        // 'Authorization': 'Bearer TOKEN',

      },
      method: 'POST',
      mode: 'no-cors',
      credentials: 'include',
      body: 'grant_type=&username=charl%40mavencodom&password=test&scope=&client_id=&client_secret='
    });
  } catch( error ) {
    // manage errors here
  }
  return response;
}

© www.soinside.com 2019 - 2024. All rights reserved.