【发布时间】: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