【问题标题】:res.cookie ist not saved in the browserres.cookie 没有保存在浏览器中
【发布时间】: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: ''
        })
    }

图片:

Setting up cors

这是 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


【解决方案1】:

您将 cookie 存储在服务器中。供您存储在客户端。返回cookie并使用客户端中的静态js文件存储。

//Returned cookie
document.cookie = "auth_token=token returned by server;

【讨论】:

  • 哇!!! @adarsh storing in the server 是什么意思? ?
猜你喜欢
  • 2019-09-07
  • 2019-05-16
  • 2017-06-30
  • 2013-05-04
  • 2022-11-02
  • 2021-07-20
  • 2021-12-10
  • 2020-02-27
  • 1970-01-01
相关资源
最近更新 更多