Skip to content

Instantly share code, notes, and snippets.

@vimal-verma
Created June 18, 2021 04:43
Show Gist options
  • Save vimal-verma/63d67762a89b1d6de1b304b911399bb0 to your computer and use it in GitHub Desktop.
Save vimal-verma/63d67762a89b1d6de1b304b911399bb0 to your computer and use it in GitHub Desktop.
For cookies based auth in MERN
import React, {useState} from 'react'
import axios from 'axios'
export default function Image() {
axios.defaults.baseURL = http://localhost:5000
const [User, setUser] = useState({);
const handleSubmit = (e) => {
e.preventDefault();
axios.post(`/register`,User,{withCredentials: true})
.then(res =>{
console.log("register success")
})
.catch(err => {
console.log(err)
})
};
return (
<form onSubmit={handleSubmit}>
<input type="name" name="name" onChange={e=>setUser({...User, name: e.target.value })} value={User.name} required />
<input type="email" name="email" onChange={e=>setUser({...User, email: e.target.value })} value={User.email} required />
<input type="password" name="password" onChange={e=>setUser({...User, password: e.target.value })} value={User.password} required />
<button type="submit">Add</button>
</form>
)
}
// server
const express = require('express');
const mongoose = require('mongoose');
require('dotenv').config()
var cors = require('cors')
const cookieParser = require('cookie-parser');
// mongodb setup
const dbURI = process.env.DB_URL;
mongoose.connect(dbURI, { useNewUrlParser: true, useUnifiedTopology: true })
.then(result => console.log('connected to db'))
.catch(err => console.log(err));
const app= express();
app.use(express.json())
app.use(cors())
app.use(cookieParser());
app.post('/register',(req,res)=>{
const user = new User({
email : req.user.email,
displayName : req.user.name,
password : req.user.password,
})
user.save()
.then(usersaved => {
const accesstoken = jwt.sign({result:usersaved}, process.env.ACCESSTOKEN,{expiresIn: '30d'})
res.cookie('token',accessToken, { maxAge: 30*24*60*60*1000, httpOnly: true })
res.json(accessToken)
})
.catch(err => {
console.log('error in saving user')
res.status(400).send(err)
})
})
const port = process.env.PORT || 5000
app.listen(port, console.log(`app is running on port ${port}, go to http://localhost:${port}`))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment