【问题标题】:Failed to fetch Error - How do I send an axios response in Polka?无法获取错误 - 如何在 Polka 中发送 axios 响应?
【发布时间】:2021-08-15 01:27:19
【问题描述】:

我尝试在 Svelte/Sapper 应用程序中获取登录数据,如下面的代码所示,我使用 polka 和 axios 来处理服务器上的 api 请求。

我不明白 axios 调用中的行为。 console.log(JSON.stringify(result.data)) 记录了我预期的正确结果。但是客户端的 fetch 请求会抛出这个异常:

错误:获取失败

谁能解释我做错了什么?

//client
try {
      const res = await fetch("login.json", {
        method: "POST",
        headers: {"Content-Type": "application/json"},
        body: JSON.stringify({ user: email, passw: password }),
      });
      let result = await res.json();
     
      if (!res) {
        throw new Error(result.error);
      }else{
        console.log("result: "+JSON.stringify(result));
      }
    } catch (e) {
      error = e.message;
      console.log("Error: "+error); //Error: Failed to fetch
    }
  }
//server
export async function post(req, res) {
    const password = sha3_512(req.body.password);
    const qs = require('qs');
    const data = qs.stringify({ user: req.body.user, password: password })
    const config = {
        method: 'post',
        url: 'https://****login',
        httpsAgent: agent,
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        },
        data: data
    }
    
    axios(config)
    .then(result => {
        console.log(JSON.stringify(result.data));//successful response
        res.end(JSON.stringify(result.data));
    })
    .catch(err => res.end(err));
}

【问题讨论】:

  • 我刚刚看到,如果我打开 Chrome DevTools,获取请求就会起作用。但是一旦我关闭 DevTools,它就不再工作了,它会抛出“无法获取”错误。这对我来说看起来很奇怪。这可能是关于 CORS 的任何问题吗?

标签: axios svelte sapper polka


【解决方案1】:

在表单元素中添加preventDefault后问题解决。

 <form on:submit|preventDefault={() => submit()}>

【讨论】:

    猜你喜欢
    • 2019-05-06
    • 1970-01-01
    • 1970-01-01
    • 2021-01-31
    • 2020-08-10
    • 2018-12-30
    • 2015-06-06
    • 1970-01-01
    • 2022-08-03
    相关资源
    最近更新 更多