首页 > 解决方案 > Axios 发布到 api 时没有返回响应,但是如果 URL 中有错误,错误处理会起作用

问题描述

我正在发布到我的 API 并且它应该返回响应的地方没有记录到控制台。

我有以下代码:

import React, {useState} from "react"
import axios from 'axios';

const conn = axios.create({
  baseURL: 'https://myurl.com',
  headers: {
    'Content-Type': 'application/json'
  }
});

const Login = () => {
  const [un,setUn] = useState('');
  const [pw,setPw] = useState('');

  const pleaseLogin = (un, pw) => {

      //Hard coding the values for now
      const email = "me@mydomain.org";
      const pass = "weakpassword";

      conn.post('/apilogin/authenticate/',
        {
          email: email, password: pass
        })
      .then(res => {
        console.log("This is never reached");
        console.log(res);
        console.log(res.data);
      }, (error) => {
        console.log("This is reached if I alter the URL");
        console.log(error);
      });
  }

  return (
    <form onSubmit={() => pleaseLogin(un,pw)}>
      <label>
        User Name:
        <input type="text" value={un} onChange={setUn} />
      </label>
      <label>
        Password:
        <input type="text" value={pw} onChange={setPw} />
      </label>
      <input type="submit" value="Submit" />
    </form>
  );
};

export default Login

如果我更改 URL,则会收到 404 错误,因此错误处理正在工作,但如果 URL 正确,则根本不会记录任何响应。如果我通过邮递员运行对 API 的调用,那么它工作正常,我得到如下 JSON 响应:

{
    "refresh": "tokendata",
    "access": "tokendata"
}

尝试使用 fetch 时,我在记录响应时看到了 CORS 错误,但是由于添加了 cors 设置它停止了,但我仍然没有看到响应。我可以看到服务器上没有错误,处理请求时我只看到200OK。

这是使用 Fetch 方法:

const pleaseLogin = async (un, pw) => {

  const data = { email: un, password: pw };

  fetch(`${baseUrl}/apilogin/authenticate/`, {
    method: 'POST', // or 'PUT'
    headers: {
      'Content-Type': 'application/json',
    },
    mode: 'cors',
    body: JSON.stringify(data),
  })
  .then(response => {console.log(response)});
}

我已经尝试从 http://localhost:3000 和 http://myipaddress:3000 运行 react,但这并没有什么不同。

服务器日志:

   2020-12-03T10:04:37.365435+00:00 heroku[router]: at=info method=POST path="/apilogin/authenticate/" host=OMITTED fwd="myexternalipaddress" dyno=web.1 connect=0ms service=200ms status=200 bytes=761 protocol=https
2020-12-03T10:04:37.363496+00:00 app[web.1]: omitted - - [03/Dec/2020:10:04:37 +0000] "POST /apilogin/authenticate/ HTTP/1.1" 200 438 "http://localhost:3000/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36"

更新:修改了下面的标题。

headers: {
  'Content-Type': 'application/json',
  'Sec-Fetch-Site': 'cross-site',
},

更新:我尝试在运行 API 后端的开发服务器上运行 react 应用程序。django 应用程序设置为处理 CORS。我尝试使用 Firefox,服务器收到如下请求:

OPTIONS /api/authenticate/ HTTP/1.1" 200 0

如果我在 Chrome 中运行该应用程序,那么它什么也得不到。我了解这是飞行前的请求。据我所知,服务器已设置为处理此问题。我不知道从这里去哪里。我知道其他框架可以处理相同的请求。我已经使用下面的静态 HTML 进行了测试,并且可以正常工作。

<script>


const login = async () => {

  const email = "emailaddress";
  const pass = "password";

  try {
    const response = await axios({
      'Content-Type' : 'application/json',
      url: 'http://127.0.0.1:8000/api/authenticate/',
      method: 'post',
      data: { email: email, password: pass },
    }).then( response => {
      console.log(response);
    });
  } catch (e) {
    console.log(e);
  }
}

login();

</script>

标签: reactjsaxios

解决方案


尝试添加"proxy": "http://localhost:3000"到您package.jsonclient文件夹中(以克服 CORS 问题)。:-

  • /client/package.json
{
  "name": "proj_name",
  "version": "0.1.0",
  "proxy": "http://localhost:3000"
}

然后,添加async await到您的res(很多时候我确实偶然发现了这个问题,这对我有帮助):-

  • Login.js:-
import React, {useState} from "react"
import axios from 'axios';

const conn = axios.create({
  baseURL: 'https://myurl.com',
  headers: {
    'Content-Type': 'application/json'
  }
});

const Login = () => {
  const [un,setUn] = useState('');
  const [pw,setPw] = useState('');

  const sayHello = () => {
    console.log("hello");
  }

  const pleaseLogin = (un, pw) => {

      //Hard coding the values for now
      const email = "me@mydomain.org";
      const pass = "weakpassword";

      conn.post('/apilogin/authenticate/',
        {
          email: email, password: pass
        })
      .then(async res => {
        const result = await res
        console.log("This is never reached");
        console.log(result);
        console.log(result.data);
      }, (error) => {
        console.log("This is reached if I alter the URL");
        console.log(error);
      });
  }

  return (
    <form onSubmit={() => pleaseLogin(un,pw)}>
      <label>
        User Name:
        <input type="text" value={un} onChange={setUn} />
      </label>
      <label>
        Password:
        <input type="text" value={pw} onChange={setPw} />
      </label>
      <input type="submit" value="Submit" />
    </form>
  );
};

export default Login

推荐阅读