程序问答   发布时间:2022-06-02  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了CORS express js 不保存 cookie大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

如何解决CORS express js 不保存 cookie?

开发过程中遇到CORS express js 不保存 cookie的问题如何解决?下面主要结合日常开发的经验,给出你关于CORS express js 不保存 cookie的解决方法建议,希望对你解决CORS express js 不保存 cookie有所启发或帮助;

我阅读了很多这样的问题,但没有一个对我有用。 我有一个 MERN 应用程序。我使用 Heroku 进行部署。在我的本地环境中一切正常,但在 heroku 中登录崩溃。我使用饼干。并尝试所有可能的配置。

请帮忙。

这是我的登录服务器:

 

    login: async (req,res) => {
            try {
                const { email,password } = req.body;
                const user = await Users.findOne({ email })
                //console.log(user)
                if (!user) return res.status(400).Json({ msg: "Usuario inexistente" })
    
                const ismatch = await bcrypt.compare(password,user.password)
                if (!ismatch) return res.status(400).Json({ msg: "Clave erronea" })
    
                //If login success,craete access Token and refresh
                const accesstoken = createAccesstoken({ ID: user._ID })
                const refreshtoken = createrefreshToken({ ID: user._ID })
    
                //console.log(refreshtoken)
                res.cookie('refreshtoken',refreshtoken,{
                    sameSite: 'Strict',httpOnly: true,path: '/user/refresh_token',maxAge: 7 * 24 * 60 * 60 * 1000 //7days
                })
                res.Json({ accesstoken })
    
            } catch (err) {
                return res.status(500).Json({ msg: err.message })
            }
        },

这里是服务器配置。


    //MIDDELEWARES
    app.use(express.Json())
    app.use(cookieParser())
    //app.use(cors())
    /*app.use(cors({
        credentials: true,origin: 'https://gabymanualIDades.herokuapp.com/'
      }))*/
    app.use(cors({origin: 'https://*****.herokuapp.com',methods: ['POST','PUT','GET','OPTIONS','head'],credentials: true,headers: 'Authorization,X-API-KEY,Origin,X-requested-With,Content-Type,Accept,Access-Control-Allow-request-Method' }))
    app.use(fileUpload({
        useTempfiles: true
    }))

和客户:


    const loginsubmit = async e => {
            e.preventDefault()
            try {
                //await axios.post('/user/login',{ ...user })
                const res=await axios.post('/user/login',{ ...user },{
                    headers: {
                        'Content-Type': 'application/Json'
                    },withCredentials: true,baseURL: "*****.herokuapp.com"
                })
    
                console.log(res)
    
                localstorage.setItem('firstLogin',truE)
    
                //window.LOCATIOn.href = "/products";
            } catch (err) {
                alert(err.response.data.msg)
            }
        }

非常感谢!


截图:

CORS express js 不保存 cookie

就好像我没有保存cookie就登录了一样,从那以后我再也无法在这里获取它了:


    useEffect(() => {
            const firstLogin = localstorage.getItem('firstLogin')
            if (firstLogin) refreshToken()
        },[])
    
        const refreshToken = async () => {
            try {
                console.log("aca problema")
                const res = await axios.get('/user/refresh_token',baseURL: "https://young-wilDWood-03509.herokuapp.com/"
                })
                setToken(res.data.accesstoken)
                setTimeout(() => {
                    refreshToken()
                },10 * 60 * 1000)
                
            } catch (err) {
                alert(err.response.data.msg)
            }
        }

服务器:


    refreshToken: (req,res) => {
            try {
                //console.log(req.cookies)
                const rf_token = req.cookies.refreshtoken;
                if (!rf_token) return res.status(401).Json({ msg: "Plase Login or registeer" })
    
    
                jwt.verify(rf_token,process.env.refresH_TOKEN_SECRET,(err,user) => {
                    if (err) return res.status(400).Json({ msg: "Plase Login or registerr" })
                    const accesstoken = createAccesstoken({ ID: user.ID })
                    //res.Json({user,accesstoken})
                    console.log({ accesstoken })
                    res.Json({ accesstoken })
                })
    
                //res.Json({ rf_token })
            } catch (err) {
                return res.status(500).Json({ msg: err.message })
            }
    
        },

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

大佬总结

以上是大佬教程为你收集整理的CORS express js 不保存 cookie全部内容,希望文章能够帮你解决CORS express js 不保存 cookie所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。