【问题标题】:Can't send/receive cookies to backend reactJS无法向后端 reactJS 发送/接收 cookie
【发布时间】:2021-08-08 02:25:14
【问题描述】:

我一直在尝试注册、登录,然后从我的后端获取一些“挑战(一些数据)”。我已成功注册并登录。但是,当我请求挑战时,我收到一条消息,说“没有找到 cookie”。我尝试将“withcredentials”设置为每个可能的值,但我无法弄清楚为什么会出现此错误。我使用一个简单的“create-react-app”重新创建了我的代码:

import logo from './logo.svg';
import './App.css';

function App() {

  const create = async (id) => {
    const myPost = {
      
      username: "foo",
      password: "bar",
    }
    const res = await fetch('http://localhost:3001/users/createUser',
    {
      method: 'POST',
      headers: {
        'Content-type': 'application/json',
        'Accept': 'application/json'
      },
      body: JSON.stringify(myPost),
      credentials: "include"
    }
    )
    const data = await res.json()
    console.log(data)
  }
  const login = async (id) => {
    const myPost = {
      
      username: "foo",
      password: "bar",
    }
    const res = await fetch('http://localhost:3001/users/login',
    {
      method: 'POST',
      headers: {
        'Content-type': 'application/json',
        'Accept': 'application/json'
      },
      body: JSON.stringify(myPost),
      credentials: "include"
    }
    )
    const data = await res.json()
    console.log(data)  }
  const getChall = async (id) => {
    const myPost = {
      
      username: "foo",
      password: "bar",
    }
    const res = await fetch('http://localhost:3001/challenges/getAllActive',
    {
      method: 'GET',
      headers: {
        'Content-type': 'application/json',
        'Accept': 'application/json'
      },
      credentials:'same-origin'
    }
    )
    const data = await res.json()
    console.log(data)
    
  }
  return (
    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <p>
          Edit <code>src/App.js</code> and save to reload.
        </p>
        <a
          className="App-link"
          href="https://reactjs.org"
          target="_blank"
          rel="noopener noreferrer"
        >
          Learn React
        </a>
      </header>
      <button onClick={create}>create </button>
      <button onClick={login}>login </button>
      <button onClick={getChall}>getChall </button>
    </div>
  );
}

export default App;

还有一些来自后端的代码:

const getAllActive = async (req,res) => {
    const allActive = [];
    for (var index in req.user.activeChallenges){
        allActive.push(await Challenge.findById(req.user.activeChallenges[index].challengeId));
    }
    res.json(allActive);
};```

【问题讨论】:

    标签: reactjs react-native cookies frontend backend


    【解决方案1】:

    返回 cookie 的后端代码在哪里?通常响应会是这样的:

            res.cookie("token", token, { maxAge:1000 * 60 * 60 })
            // above cookie expires after 60 minutes
            res.end()
    

    或者这里是另一个基本的例子:

    exports.get = function(request, response, db) {
        let msg = { username: "", password: "" };
        let username;
        let password;
        if (request.body.name == 'joe'){
          msg.username = "correct";
        }else{
          msg.username = "incorrect";
        }
        if (request.body.password == 'sesame'){
          msg.password = "correct";
        }else{
          msg.password = "incorrect";
        }
        if (msg.username == 'correct' && msg.password == 'correct'){
            response.cookie('spongebob', 'squarepants').send(JSON.stringify(msg));
        } else {
            response.send(JSON.stringify(msg));
        }
    }
    

    【讨论】:

    • 对于上下文中的上述代码,请参阅 Glitch 上的这个工作示例:glitch.com/~hollow-tremendous-donkey 当您登录时,特别注意在 public/client.js 中执行的代码(它执行从客户端到服务器的获取) 和 controllers/login.js 中的代码(如果发送了正确的凭据,则返回一个 cookie)。
    猜你喜欢
    • 1970-01-01
    • 2021-09-23
    • 2017-09-02
    • 2012-07-21
    • 1970-01-01
    • 2019-09-09
    • 1970-01-01
    • 2021-08-03
    • 1970-01-01
    相关资源
    最近更新 更多