【问题标题】:Cookies are being sent but chrome doesn't set them正在发送 Cookie,但 chrome 未设置它们
【发布时间】:2022-08-23 23:18:50
【问题描述】:

我看到了许多类似的问题,并尝试了许多组合,但没有任何效果。 我指定它都在本地主机上。

    regUser = () => {
    var username = getE(\"username-input\").value;
    var email = getE(\"email-input\").value;
    var password = getE(\"password-input\").value;
    axios({
        url: process.env.REACT_APP_API_URL + \"register\",
        method: \"post\",
        data: {
            username, email, password
        },
        withCredentials: true
    }).then(res => {
        if(res.data.regSuccess) {
            // Registration successful
            this.setState({
                regSuccess: true,
                regTextHidden: false,
                regText: \"Registration Successful! An e-mail was sent to the specified e-mail address with confirmation information! You will be redirected to the Login page...\"
            }, ()=>{
                setTimeout(
                    ()=>{window.location.href=(\"/login\")}, 5000
                    )
            })
        } else {
            this.setState({
                regSuccess: false,
                regTextHidden: false,
                regText: \"An error occured. Please try again later!\"
            })
        }
    })
}

后端代码:

            f.checkPassword(userData, function(result) {
            if(!result.correct) {
                // Wrong password
                res.send({found: true, correct: false})
                
            } else {
                // Proceed with authentication
                var token = f.genToken(userData.user);
                res.header(\"OPTIONS\", \'true\')
                res.cookie(\"access-token\", token.token, {httpOnly: true, sameSite: \"none\", maxAge: \"100000\", secure: false});
                res.send({found: true, correct: true})
            }
        })

无论我使用什么 cookie 设置,它们都会被发送,\"Set-Cookie\" 标头存在,但没有设置 cookie。

我已经使用每个选项玩了 2 天,但它只是不起作用。有什么建议吗?

  • 可能的答案在这里:stackoverflow.com/questions/36824106/…
  • 尝试了所有答案,但没有一个有效:(
  • 编辑:我累了,我试图在反应中编辑一个不同的请求......它有效!

标签: reactjs express cookies localhost


【解决方案1】:

我也被困了一段时间。有几件事为我解决了这个问题:

在 axios 调用的前端(我看到你已经完成了),使用:

withCredentials: true

然后在express的后端,使用npm包cors,如下:

const app = express();
app.use(cors({ credentials: true, origin: 'http://localhost:3000' }));

或者使用您的网址来源。希望这对你有用。

【讨论】:

    猜你喜欢
    • 2017-09-24
    • 2015-07-04
    • 1970-01-01
    • 2011-11-03
    • 1970-01-01
    • 2014-08-02
    • 2021-11-03
    • 2017-03-06
    • 2011-11-12
    相关资源
    最近更新 更多