首页 > 解决方案 > 发帖请求出错

问题描述

我正在尝试挑战,我必须通过发布请求将这些数据发送到http://challenge-react.alkemy.org/

email: challenge@alkemy.org
password: react
const baseUrl = "http://challenge-react.alkemy.org/";

const user = {
    'email': 'challenge@alkemy.org',
    'password': 'react'
    
}

const getToken =  async () => {
    fetch(baseUrl, {
        method: 'POST',
        request: {"Content-Type": "application/json"},
        body: JSON.stringify(user)
    })
    .then(response => response.json()) 
    .then(json => console.log(json))
    .catch(err => console.log(err));
}

export default getToken;

出于某种我无法理解的原因,它正在把这个还给我

{错误:“请提供有效的电子邮件和密码”}

我不知道我的问题是我的功能还是什么。如果我通过邮递员发出同样的请求,它会返回我需要的令牌

标签: reactjsapipostrequest

解决方案


我认为这在浏览器中永远不会起作用,因为它不断强制请求结束HTTPS,错误:(unknown) POST https://challenge-react.alkemy.org/ net::ERR_SSL_PROTOCOL_ERROR。您可以通过在开发人员工具中打开控制台选项卡(Chrome 上的 F12)来检查自己。

function App() {
  const baseUrl = "http://challenge-react.alkemy.org";

  const user = {
    email: "challenge@alkemy.org",
    password: "react",
  };

  React.useEffect(() => {
    fetch(baseUrl, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify(user),
    })
      .then((response) => response.json())
      .then((json) => console.log(json))
      .catch((err) => console.error(err)); // "oh, no!"
  }, []);
  return <div />;
}
ReactDOM.render(<App />, document.getElementById("root"));
<div id="root"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>


推荐阅读