how to retrieve jwt stored in cookies - node.js

I am exercising authentication for MERN stack and I decided to store JWT inside cookies, where during login new token will be sent to the cookies and during logout the function checks for the token from the request and clears the cookie and removes the token from database. I can send the cookie inside node with res.cookie on http://localhost:3000/ without errors and see the content from chrome application, but when I console.log the cookie with req.cookies from http://localhost:3000/main, it is undefined
backend
server.js
const express = require("express");
const app = express();
require("dotenv").config();
const cors = require("cors");
const cookieParser = require("cookie-parser");
const dbConnect = require("./dbConnect");
const authRoutes = require("./routes/auth");
const refreshTokenRoutes = require("./routes/refreshToken");
const port = process.env.PORT;
dbConnect(); //connect to mongoDb database
app.use(
cors({
// origin: "http://localhost:3000/main",
origin: ["http://localhost:3000", "http://localhost:3000/main"],
methods: "GET, POST, UPDATE, DELETE",
credentials: true,
})
);
app.use(express.json());
app.use(cookieParser());
app.use("/api", authRoutes);
app.use("/api/refreshToken", refreshTokenRoutes);
app.get("/", (req, res) => {
res.send("hello");
});
app.listen(port, () => {
console.log(`listening on http://localhost:${port}`);
});
auth.js
router.post("/login", async (req, res) => {
try {
//check if the input is in a valid format
const { error } = logInBodyValidation(req.body);
if (error) {
res.status(400).json({ error: true, message: error.details[0].message });
}
//check if the user is registered in the database
const user = await users.findOne({
email: req.body.email,
});
const passwordCheck = await bcrypt.compare(
req.body.password,
user.password
);
if (!user || !passwordCheck) {
res
.status(401)
.json({ error: true, message: "invalid email or password" });
}
const { accessToken, refreshToken } = await generateToken(user);
res
.cookie("jwtoken", refreshToken, {
maxAge: 1296000000,
path: "/",
domain: "localhost:3000",
httpOnly: true,
})
.status(200)
.json({
error: false,
accessToken,
refreshToken,
message: "Logged in sucessfully!",
});
} catch (error) {
// res.status(500).json({ error: true, message: "Internal Server Error" });
}
});
req.cookies returns the cookies
refreshToken.js
// logout
router.get("/", async (req, res) => {
try {
const { error } = refreshTokenBodyValidation(req.user);
if (error)
return res
.status(400)
.json({ error: true, message: error.details[0].message });
const userToken = await UserToken.findOne({
token: req.user.refreshToken,
});
if (!userToken)
return res
.status(200)
.json({ error: false, message: "Logged Out Sucessfully!" });
await userToken.remove();
res
.clearCookie("jwtoken")
.status(200)
.json({ error: false, message: "Logged Out Sucessfully!" });
} catch (error) {
console.log(error)
}
});
req.cookies returns [Object: null prototype] {}
Frontend
Login.js
import React from "react";
const Login = ({ email, password, setEmail, setPassword }) => {
const loginUser = async (e) => {
e.preventDefault();
try {
const response = await fetch("http://localhost:5000/api/login", {
headers: {
"Content-type": "application/json",
},
method: "POST",
credentials: "include",
body: JSON.stringify({
email,
password,
}),
});
const data = await response.json();
localStorage.setItem("token", data);
console.log(data);
// window.location.href = "/main";
} catch (error) {
console.log(error);
}
};
return (
<div className="container">
<h1>Login</h1>
<form onSubmit={loginUser}>
<input
title="Email"
// value={email}
placeholder="Enter E-mail"
type="email"
className="email"
onChange={(e) => {
setEmail(e.target.value);
}}
/>
<input
title="Password"
// value={password}
placeholder="Enter Password"
type="password"
className="pass"
onChange={(e) => {
setPassword(e.target.value);
}}
/>
<button>Log in</button>
</form>
</div>
);
};
export default Login;
Logout.js
import React from "react";
const Logout = () => {
const logoutUser = async () => {
const response = await fetch("http://localhost:5000/api/refeshToken/", {
headers: {
"Content-type": "application/json",
},
method: "GET",
});
const data = await response.json();
if (data.user) {
alert("Logged out successfuly");
window.location.href = "/";
}
};
return (
<div className="logout">
<button
className="logout_button"
title="Logout"
onClick={(e) => logoutUser(e)}
>
Log out
</button>
</div>
);
};
export default Logout;

the problem was a CORS error, must include credentials: "include" in the logout fetch request header

Related

Cookie found in the res headers but it's not loaded by the browser

in my server side (nodejs )
const passport = (res, user, statusCode) => {
const jwt_ = jwt.sign({ id: user._id }, process.env.JWTSECRET, {
expiresIn: process.env.JWTSECRETEXPIRES,
});
res.cookie("jwt", jwt_, {
expires: new Date(
Date.now() + process.env.COOKIESEXPIRES * 24 * 60 * 60000
),
httpOnly: false,
secure: false,
});
res.status(statusCode).json({
status: "success",
user,
jwt: jwt_,
});
}
const login = catchAsync(async (req, res, next) => {
const { email, password } = req.body;
if (!email || !password)
return next(
new AppError(400, "you should provide your email and password")
);
const user = await User.findOne({ email }).select("+password");
if (!user || !(await user.isCorrectPassword(password)))
return next(new AppError(400, "incorrect email or password "));
passport(res, user, 200);
});
in my next.js app i try to send a login request
const Login = () => {
const email = useRef(null);
const password = useRef(null);
return (
<form
onSubmit={async (e) => {
e.preventDefault();
const res = await axios.post(
"http://127.0.0.1:3000/api/v1/users/login",
{
email: email.current.value,
password: password.current.value,
},
{ withCredentials: true }
);
}}
>
<input ref={email} />
<input ref={password} />
<button>login</button>
</form>
);
};
export default Login;
the problem is the Cookie found in the res headers but it's not loaded by the browser !!
this is my the cors config in my app.js:
app.use(cookieParser());
app.use(express.json());
app.use(
cors({
withCredentials: true,
credentials: true,
origin: "http://localhost:3001",
})
);
it would be helpful to know where is exactly the problem
I think you should use port 3000 in the cors config.
Even if you face any issue do refer this

Login form not redirecting to home page - even though login credentials appear to match those in database

I've got a login-form that is supposed to redirect to the homepage of my React app, if the user's login detail match those already in the MongoDB database (I've got a seperate sign-up form that is working fine).
The issue is, when I'm testing out my login-form, and purposefully typing in credentials that don't match what's in my database, I get this error :
Login.js:44 POST http://localhost:3001/login 401 (Unauthorized)
However, when I type in credentials that do exist - that error no longer appears, but I get the console.log error I've set up - ("login failed")
Why am I getting this error, instead of the app redirecting to the homepage?
It's clearly able to connect to the database and check if the login details stored in there match the user's input.
What else could be causing this issue?
I've also tried altering the url endpoints, but no luck.
This is the login form code
import React from "react";
import Input from "./Input";
import { useForm } from "react-hook-form";
import { yupResolver } from "#hookform/resolvers/yup";
import * as yup from "yup";
import {
useLocation,
useNavigate,
useParams
} from "react-router-dom";
function withRouter(Component) {
function ComponentWithRouterProp(props) {
let location = useLocation();
let navigate = useNavigate();
let params = useParams();
return (
<Component
{...props}
router={{ location, navigate, params }}
/>
);
}
return ComponentWithRouterProp;
}
const schema = yup.object({
username: yup.string().required("Username is a required field"),
password: yup.string().min(6, "Password must be at least 6 characters"),
});
function Login(props) {
const {
handleSubmit,
register,
formState: { errors },
} = useForm({
resolver: yupResolver(schema),
});
const formSubmit = (data) => {
fetch("http://localhost:3001/login", {
method: "POST",
body: JSON.stringify({username: data.username, password: data.password}),
headers: { "Content-Type": "application/json" },
})
.then((response) => {
if (response.status === 200 && props.history) {
props.history.push("/");
} else {
console.log("login failed");
}
})
.catch((error) => {
console.error("Error:", error);
});
console.log(data);
};
return (
<div className="sign-up">
<h1>Log in</h1>
<p>Lorem ipsum dolor, sit amet consectetur</p>
<form onSubmit={handleSubmit(formSubmit)}>
<Input
id="username"
label="Username"
type="text"
placeholder="Enter Username"
register={{ ...register("username") }}
errorMessage={errors.username?.message}
/>
<Input
id="password"
label="Password"
type="password"
placeholder="Enter Password"
register={{ ...register("password") }}
errorMessage={errors.password?.message}
/>
<button>Log in</button>
</form>
<button className="button-link" onClick={() => props.onFormSwitch("signup")}>
Don't have an account? Register here.
</button>
</div>
);
}
export default withRouter(Login);
And this is the server-side
const express = require("express");
const app = express();
const cors = require("cors");
const mongoose = require("mongoose");
const session = require("express-session");
const passport = require("passport");
const Signup = require("./db/dbModel");
const LocalStrategy = require("passport-local").Strategy;
app.use(cors());
app.use(express.json());
mongoose.connect("..removed for StackOverflow Question");
app.use("/", require("./routes/signupRoute"));
app.use(session({ secret: "secret", resave: true, saveUninitialized: true }));
app.use(passport.initialize());
app.use(passport.session());
passport.use(
'local',
new LocalStrategy(function (username, password, done) {
Signup.findOne({ username: username }, function (err, user) {
if (err) {
return done(err);
}
if (!user) {
return done(null, false);
}
if (user.password != password) {
return done(null, false);
}
return done(null, user);
});
})
);
passport.serializeUser((user, done) => {
done(null, user.id);
});
passport.deserializeUser((id, done) => {
Signup.findById(id, (err, user) => {
done(err, user);
});
});
app.post("/login", (req, res, next) => { // test tomorrow
passport.authenticate("local", (err, user, info) => {
if (err) {
return next(err);
}
if (!user) {
return res.status(401).json({ message: "Incorrect username or password" });
}
req.logIn(user, (err) => {
if (err) {
return next(err);
}
return res.status(200).json({ message: "Successfully logged in" });
});
})(req, res, next);
});
/*
app.post("/login", passport.authenticate("local", {
successRedirect: "/",
failureRedirect: "/login",
failureFlash: true
}));
*/
app.listen(3001, function () {
console.log("express server is running on port 3001");
});
I've changed the function in the login form to this.
fetch("http://localhost:3001/login", {
method: "POST",
body: JSON.stringify({ username: data.username, password: data.password }),
headers: { "Content-Type": "application/json" },
})
.then((response) => {
if (response.status === 200) {
props.router.navigate("/");
} else {
console.log("login failed");
}
})
.catch((error) => {
console.error("Error:", error);
});
console.log(data);
};
For some reason, the props.history.push was causing the error - so it's been altered to props.router.navigate

getting undefined of an array of errors

I am having an issue with my React Redux and Node app. I am trying to Log in an existing user but in my console i am getting the following error:
Uncaught (in promise) TypeError: error.response.data is undefined
The console points to the following block of code:
export const login = (email, password) => async (dispatch) => {
const body = { email, password };
try {
const res = await axios.post('http://localhost:5000/api/auth', body);
dispatch({
type: LOGIN_SUCCESS,
payload: res.data
});
dispatch(loadUSer());
} catch (err) {
const errors = err.response.data.errors;
if (errors) {
errors.forEach((error) => dispatch(setAlert(error.msg, 'danger')));
}
dispatch({
type: LOGIN_FAIL
});
}
};
This is my server side for user auth auth.js:
const express = require('express');
const router = express.Router();
const User = require('../../models/User');
const auth = require('../../middleware/auth');
const config = require('config');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const { check , validationResult } = require('express-validator/');
//#route GET api/auth
//#desc Test route
//#access public
router.get('/',auth, async(req, res)=> {
try{
const user = await User.findById(req.user.id).select('-password');
res.json(user);
}catch(err){
console.error(err.message);
res.status(500).send('Server Error');
}
});
//#route POST api/auth
//#desc Authenticate user & get token
//#access public
router.post('/', [
check('email', 'Plese include a valid email').isEmail(),
check('password', 'Password is required').exists()
],
async (req, res)=> {
const errors = validationResult(req);
if(!errors.isEmpty()){
return res.status(400).json({ errors:errors.array()}); //400 is for bad requests
}
const { email, password } = req.body;
try{
//See if user exists
let user = await User.findOne({ email });
if(!user){
return res.status(400).json({ errors: [{ msg:'Invalid credentials' }] });
}
//Compare the input password, plane text, to the encrypted password.
const isMatch = await bcrypt.compare(password, user.password);
if(!isMatch){
return res.status(400).json({ errors: [{ msg:'Invalid credentials' }] });
}
//Return jsonwebtoken -> this for users to be logged in right after registration
const payload = {
user:{
id: user.id
}
}
jwt.sign(
payload,
config.get('jwtSecret'),
{expiresIn: 360000}, //change to 3600 for production
(err, token)=>{
if(err) throw err;
res.json({ token });
}
)
}catch(err){
console.error(err.message);
res.status(500).send('Server Error');
}
});
module.exports = router;
And this is my Login component:
import React, { Fragment, useState } from 'react'
/* import axios, { Axios } from 'axios'; */
import { Link, Navigate } from 'react-router-dom'
import { connect } from 'react-redux';
import { PropTypes } from 'prop-types';
import { login } from '../../actions/auth';
const Login = ({ login, isAuthenticated }) => {
const [formData, setFormData] = useState({
email: '',
password: ''
});
const { email, password } = formData;
const onChange = e => setFormData({
...formData, [e.target.name]:e.target.value
});
const onSubmit = async e => {
e.preventDefault();
login(email, password);
}
//Redirect if logged in
if(isAuthenticated){
return <Navigate to="/dashboard"/>;
}
return (
<Fragment>
<section className='container'>
<h1 className="large text-primary">Sign Up</h1>
<p className="lead"><i className="fas fa-user"></i> Sign Into Your Account</p>
<form className="form" action="create-profile.html" onSubmit={e => onSubmit(e)}>
<div className="form-group">
<input type="email"
placeholder="Email Address"
name="email" value={email}
onChange={e => onChange(e)}
required/>
</div>
<div className="form-group">
<input
type="password"
placeholder="Password"
name="password"
minLength="6"
value={password}
onChange={e => onChange(e)}
required
/>
</div>
<input type="submit" className="btn btn-primary" value="Login" />
</form>
<p className="my-1">
Don´t have an account? <Link to="/register">Sign up</Link>
</p>
</section>
</Fragment>
)
}
Login.propTypes = {
login: PropTypes.func.isRequired,
isAuthenticated: PropTypes.bool
}
const mappedStateToProps = state => ({
isAuthenticated: state.auth.isAuthenticated
})
export default connect(mappedStateToProps , { login })(Login)
For some reason there are sometimes i am able to login and sometimes i encounter this issue but i cannot figure out what am i doing wrong.
My redux devtools also show the AUTH_ERROR action type:
This is my auth.js in my actions directory.
export const loadUSer = () => async dispatch => {
if(localStorage.token){
setAuthToken(localStorage.token);
}
try {
const res = await axios.get('http://localhost:5000/api/auth');
dispatch({
type: USER_LOADED,
payload: res.data
})
} catch (error) {
dispatch({
type:AUTH_ERROR
})
}
}
auth.js (reducers directory):
import{
REGISTER_FAIL,
REGISTER_SUCCESS,
USER_LOADED,
AUTH_ERROR,
LOGIN_SUCCESS,
LOGIN_FAIL,
LOGOUT
} from '../actions/types'
const initialState = {
token: localStorage.getItem('token'),
isAuthenticated: null,
loading: true,
user: null
}
function authReducer(state = initialState, action){
const { type, payload } = action
switch (type) {
case USER_LOADED:
return {
...state,
isAuthenticated:true,
loading: false,
user:payload
}
case LOGIN_SUCCESS:
case REGISTER_SUCCESS:
localStorage.setItem('token', payload.token);
return {
...state,
...payload,
isAuthenticated: true,
loading: false
}
case LOGOUT:
case LOGIN_FAIL:
case REGISTER_FAIL:
case AUTH_ERROR:
localStorage.removeItem('token');
return {
...state,
toke: null,
isAuthenticated: false,
loading: false
}
default:
return state;
}
}
export default authReducer
So i first log in with an user everything works fine, i logout and log in with a different user and also works, i now logout and want to login to the first user again and the error shows up. The only difference between both users is that one has a profile and the other one doesn´t.
When i try to log in with the user with no profile my app crashes and my vscode terminal shows a different errors:
Can't set headers after they are sent to the client

Pass data from react component to proxy(node server)

I set up a proxy to bypass CORS for the intended api in this react application. I'm having trouble to pass data from react component to proxy(nodeJS server). I've read a few links such as here and here but still have no clues.
/*React component*/
import React, { useState } from "react";
import axios from "axios";
export default function Mail() {
const [emailInput, setEmailInput] = useState('')
const getMail = () => {
axios.get("/list/members").then(json => {
console.log(json.data);
});
};
const subscribe = (email) => {
console.log('inside subscribe')
axios.post("/member", email)
.then(data => console.log('post succeeds'))
.catch(err => console.log(err))
}
const handleSubmit = e => {
e.preventDefault();
const email = {
email_address: `${emailInput}`,
status: "subscribed"
};
subscribe(email)
};
const handleChange = (e) => {
setEmailInput(e.target.value)
}
return (
<form onSubmit={handleSubmit}>
<input type="text" name="email" placeholder="enter your email" value={emailInput} onChange={handleChange}/>
<input type="submit" value="subscribe" />{" "}
</form>
);
}
In node server, I have
app.post("/member", (req, res) => {
const email = {
email_address: "axios1234#gmail.com",
status: "subscribed"
};
axios.post(
"https://<apilink>",
email,
{
withCredentials: true,
auth: {
username: "anystring",
password: "<apikey>"
}
}
).then(json => {
res.send(json.data)
}).catch(err => {
console.log(err);
})
});
I've checked that my conduit between react front end app and proxy server is working. I also examined both req and res in app.post("/member", (req, res) but found thatreq.body is undefined and couldn't find the email object that was passed in from react function component. Did I miss anything here?
Are you using a body-parser? If not, install body-parser and then change your code to this:
const bodyParser = require('body-parser');
app.use(bodyParser.json());
app.post("/member", (req, res) => {
const email = req.body.email_address;
axios.post(
"https://<apilink>",
email,
{
withCredentials: true,
auth: {
username: "anystring",
password: "<apikey>"
}
}
).then(json => {
res.send(json.data)
}).catch(err => {
console.log(err);
})
});

Post an object with fetch using react js and express API server

I am getting troubles with the post method in fetch because my server is receiving an empty object from the client. I've checked in the client side and can't send the value that I want to send.
This is my server:
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const mysql = require('mysql');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
// connection configurations
const mc = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '12345',
database: 'node_task_demo',
//socketPath: '/Applications/MAMP/tmp/mysql/mysql.sock'
});
// connect to database
mc.connect();
// default route
app.get('/', function (req, res) {
return res.send({ error: true, message: 'hello' })
});
// Here where I'm calling in the client side
app.get('/todos', function (req, res) {
mc.query('SELECT * FROM tasks', function (error, results, fields) {
if (error) throw error;
return res.send({ error: false, data: results, message: 'Todo list' });
});
});
// Search for todos with ‘bug’ in their name
app.get('/todos/search/:keyword', function (req, res) {
var mensaje = 'Todos search list.';
let keyword = req.params.keyword;
mc.query("SELECT * FROM tasks WHERE task LIKE ? ", ['%' + keyword + '%'], function (error, results, fields) {
if (error) throw error;
return res.send({ error: false, data: results, message: mensaje});
});
});
// Retrieve todo with id
app.get('/todo/:id', function (req, res) {
let task_id = req.params.id;
if (!task_id) {
return res.status(400).send({ error: true, message: 'Please provide task_id' });
}
mc.query('SELECT * FROM tasks where id=?', task_id, function (error, results, fields) {
if (error) throw error;
return res.send({ error: false, data: results[0], message: 'Todos list.' });
});
});
// Add a new todo
app.post('/todo/meterla', function (req, res) {
let task = req.body.task;
if (!task) {
return res.status(400).send({ error:true, message: 'Please provide task' });
}
//var task = req.body.task;
var query = mc.query("INSERT INTO tasks SET ? ", { task: task}, function (error, results, fields) {
if (error) throw error;
console.log(task);
return res.send({ error: false, data: results, message: 'New task has been created successfully.' });
});
});
// Update todo with id
app.put('/todo', function (req, res) {
let task_id = req.body.task_id;
let task = req.body.task;
if (!task_id || !task) {
return res.status(400).send({ error: task, message: 'Please provide task and task_id' });
}
mc.query("UPDATE tasks SET task = ? WHERE id = ?", [task, task_id], function (error, results, fields) {
if (error) throw error;
return res.send({ error: false, data: results, message: 'Task has been updated successfully.' });
});
});
// Delete todo
app.delete('/todo', function (req, res) {
let task_id = req.body.task_id;
if (!task_id) {
return res.status(400).send({ error: true, message: 'Please provide task_id' });
}
mc.query('DELETE FROM tasks WHERE id = ?', [task_id], function (error, results, fields) {
if (error) throw error;
return res.send({ error: false, data: results, message: 'Task has been updated successfully.' });
});
});
// all other requests redirect to 404
app.all("*", function (req, res, next) {
return res.send('page not found');
next();
});
// port must be set to 8080 because incoming http requests are routed from port 80 to port 8080
app.listen(8081, function () {
console.log('Escuchando por el puerto 8081');
});
// allows "grunt dev" to create a development server with livereload
module.exports = app;
This is my client:
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
class App extends Component {
constructor(props) {
super(props);
this.state = {data: ""};
this.state_2 = {message: []};
this.onSubmit = this.handleSubmit.bind(this);
}
componentDidMount() {
fetch('/todo/1')
.then((response) => response.json())
.then((responseJson) =>{
this.setState({
message: responseJson.data
});
})
}
handleSubmit(e){
e.preventDefault();
var self = this;
// On submit of the form, send a POST request with the data to the server.
fetch('/todo/meterla',{
method: 'POST',
body:{
task: self.refs.task.value
}
})
.then(function(response){
return response.json()
}).then(function(body){
console.log(body);
alert(self.refs.task.value)
});
}
render() {
return (
<div className="App">
<div className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h2>Welcome to React</h2>
</div>
<form onSubmit={this.onSubmit}>
<input type="text" placeholder="task" ref="task"/>
<input type="submit"/>
</form>
<p className="App-intro">
Este es el resultado de la consulta = <b>{JSON.stringify(this.state.message)}</b>
</p>
</div>
);
}
}
export default App;
body must be stringified + don't forget the content-type
fetch('/todo/meterla',{
method: 'POST',
body: JSON.stringify({
task: self.refs.task.value
}),
headers: {"Content-Type": "application/json"}
})
.then(function(response){
return response.json()
}).then(function(body){
console.log(body);
alert(self.refs.task.value)
});
try using axios instead of fetch
I rewrote ur code like this and it works perfectly
server
const express = require('express');
const { Client } = require('pg');
const bodyParser = require('body-parser');
const app = express();
const cors = require("cors");
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.post('/api/insertUsers', function(req, res) {
// console.log(req);
console.log(req.body);
res.send(req.body);
});
app.listen(3001, () => {
console.log('listening on port 3001');
});
react (ensure you have axios installed)
handleSubmit(e){
e.preventDefault();
var data = {
name: "zadiki",
contact: "0705578809",
email: "zadiki",
message: "test",
}
console.log("wow");
var url = ' http://localhost:3001/api/insertUsers';
axios.post(url,data)
.then(response=>console.log(response))
.catch(e=>console.log(e))
}
Looks like this is where the issue is.
constructor(props) {
super(props);
this.state = {data: ""};
this.state_2 = {message: []};
this.onSubmit = this.handleSubmit.bind(this);
}
componentDidMount() {
fetch('/todo/1')
.then((response) => response.json())
.then((responseJson) =>{
this.setState({
message: responseJson.data
});
})
}
In componentDidMount() you are setting the state for 'message'. But that is in this.state_2.
I would recommend not having this.state_2 and instead constructing your state like this:
this.state = {
data: '',
message: []
}
try using fetch like this
fetch(url, {
method: "POST",
mode: "cors",
cache: "no-cache",
credentials: "same-origin",
headers: {
"Content-Type": "application/json; charset=utf-8",
},
redirect: "follow",
referrer: "no-referrer",
body: JSON.stringify(data)
}).then(function (response) {
return response.json();
})
.then(function (myJson) {
console.log(myJson);
});
$(document).ready(()=>{
$("#formSignUp").submit(()=>{
fetch("/auth/sign/up",{
method:'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body:$("#formSignUp").serialize(),
})
.then((response)=>response.json())
.then(response=>{
}).catch(response=>{
});
return false;
});
});

Resources