我目前正在尝试设置我的react应用程序,并将其连接到我的后端。我使用JWT来创建web tokens,然后通过cookieparser保存。
服务器运行在 http:/localhost:3000客户端正在运行。http:/127.0.0.1:8080clientpublic上运行。
现在,我试图从客户端(react)发出一个帖子请求,并尝试在浏览器中存储标记(cookie),但它不工作。它不断地将cookie保存在localhost:3000域中,而不是在客户端运行的域中。. 下面是后台和前台的相关代码。
**// This is the cors setup for Express**
app.use(cors({ origin: 'http://127.0.0.1:8080', credentials: true }))
**// This is the request router API for creating the user and the cookie (and sending it to the browser)**
router.post('/api/users', async (req, res) => {
const user = new User(req.body)
try {
await user.save()
const token = await user.generateAuthToken()
res.cookie('auth_token', token, { httpOnly: false, sameSite: 'none' })
res.set('Content-Type', 'application/json')
res.send(token)
} catch (e) {
res.status(400).send('Did not work')
}
})
**// This is the request from the client with Axios:**
axios.post('http://localhost:3000/api/users', {
name: this.state.userName,
email: this.state.userEmail,
password: this.state.userPassword,
}, {
withCredentials: true,
credentials: 'include'
})
.then( (response) => {
const data = response
console.log(data)
})
.catch( () => {
console.log('Cant access backend')
})
this.setState({
userName: '',
userEmail: '',
userPassword: ''
})
}
图片。
这是api路由器。用于创建用户并将其发送到数据库的API路由器。
这是客户端(前端)的请求发布请求,向axios注册用户
非常感谢您的帮助:)
你把cookie存储在服务器上。供你在客户端存储。返回cookie,在客户端使用静态js文件存储。
//Returned cookie
document.cookie = "auth_token=token returned by server;