Home > front end >  cookie is null when using reactjs as frontend and nodejs as backend
cookie is null when using reactjs as frontend and nodejs as backend

Time:06-20

ReactJS code

import axios from 'axios';
import {useEffect,useState} from 'react';
import ReactDOM from "react-dom/client";
import React from "react";


const App = () => {
    const [res,setRes] = useState(null)
    useEffect(() => {
        document.cookie='hello=3';
        axios.post('http://localhost:4000/hello').then(res1 => {
            setRes(res1.data)
        })
    },[])

    return (
        <div>
            {res}
        </div>
    );

}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
        <App />
);

Nodejs code

import express from 'express';
import cors from 'cors';
import bodyParser from 'body-parser'
import cookieParser from 'cookie-parser'

const PORT = 4000;
const app = express();

// cors
app.use(cors());
app.use(bodyParser.urlencoded({extended: false}));
app.use(cookieParser())


app.post('/hello', (req, res) => {
    console.log(req.cookies) 
    res.send('This is from server!')

})


app.listen(PORT, () => {

    console.log('listening on port', PORT); // eslint-disable-line no-console
});

On the line of console.log(req.cookies) in node.js it gives [Object: null prototype] {} what is the issue?

CodePudding user response:

You are sending request to a different domain. If you want to send cookies with that request you would have to add withCredentials property in request options.

axios.get(
  'http://localhost:4000/hello',
  { withCredentials: true }
);
  • Related