【发布时间】:2020-08-24 22:41:07
【问题描述】:
我目前正在尝试设置我的 React 应用程序并将其连接到我的后端。我正在使用 JWT 创建 Web 令牌,然后通过 cookieparser 保存。
服务器正在运行:http://localhost:3000/ 客户端正在运行:http://127.0.0.1:8080/client/public/
现在,我正在尝试从客户端(反应)发出一个发布请求,并尝试将令牌(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 Router for creating user and sending it to DB
这是客户端(前端)请求 Post request to register user with axios
非常感谢您的帮助:)
【问题讨论】:
-
没错.. cookie 将保存到
localhost因为您的服务器主机是 localhost.. 这是预期的行为。如果您期望它保存到您的客户域..那么抱歉。
标签: node.js reactjs cookies request cross-domain