即使在react(Fetch API)中状态为200,API也无法获取任何响应

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

我正在将 API 与我的 React 登录表单集成,但我收到 无法加载响应数据:找不到具有给定标识符的资源的数据,即使状态代码为 200。

当我在邮递员中触发 API 时,一切工作正常,但是当我将其与我的应用程序集成时,它显示错误 index.js:1 错误:语法错误:输入意外结束

let userLogIn = async function() {
        fetch('http://kishansharma.pythonanywhere.com/login', {
            method: 'POST', 
            mode: 'no-cors', 
            headers: {
              'Content-Type': 'application/x-www-form-urlencoded'
            },
            body: `email=${emailId}&password=${password}`,
        })
        .then(response => response.json())
        .then((data) => {
        console.log('Success:', data);
        })
        .catch((error) => {
        console.error('Error:', error);
        });
    }

我已经添加了集成 API 的代码,任何帮助将不胜感激。

javascript reactjs json api fetch-api
2个回答
1
投票

错误

SyntaxError: Unexpected end of input
通常 来自无效的 json 响应。 也许邮差会以文本形式向您显示原始响应。 您应该检查响应是否是有效的 json,没有语法错误。

要尝试的事情:

  • 在您的
    headers
    对象中添加以下内容:
    Accept': 'application/json'
  • 响应的 JSON 真的有效吗?有时会缺失
    }

0
投票

我遇到了同样的错误,我通过添加 e.preventDefault(); 修复了它

之前: const handleSubmit = () => { 轴 .post("http://localhost:5000/users", {name: ""}) .then((res) => console.log(res.data)) .catch((err) => console.log(err.message)); };

更正: const handleSubmit = (
e) => { e.preventDefault(); 轴 .post("http://localhost:5000/users", {name: ""}) .then((res) => console.log(res.data)) .catch((err) => console.log(err.message)); };

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