Home > Net >  Not able to access request Headers in node.js server
Not able to access request Headers in node.js server

Time:07-07

This is related to my last Question - JsonWebTokenError: jwt must be a string, node.js

I'm trying to get simple
console.log(req.header('host'),'req host')
but getting the whole header object like i will get in
console.log(req),'req').

Why I'm not able to access value of header object, I also did the Cors setting to avoid custom header to access, still no success?

Post.js (Sending the header with post request)

import React, { useEffect, useState } from 'react'
import { useParams } from 'react-router-dom';
import axios from 'axios';
import './Post.css'


function Post() {

    let { id } = useParams();

    const [postObject, setPostObject] = useState({})
    const [comments, setComments] = useState([]);
    const [newComment, setNewComment] = useState("");

    // console.log(comments)




    const addComment = () => {


        const accessToken = sessionStorage.getItem('accessToken')
        console.log(typeof (accessToken), 'acces token in comment button')


        axios.post(`http://localhost:4000/comments`, {
            commentBody: newComment,
            PostId: id
        },
            {
                headers: {
                    accessToken: accessToken,
                }
            }

        )
            .then((res) => {
               
                const data = res.data;
                console.log(data, 'comments')

                setComments([...comments, data])
                setNewComment("")
            })
            .catch((err) => {
                alert(err, 'Error:comment')
            })
    }

    return (
        <div className='Post'>

            <div className='left__side'>
                <div className='left__side__wrapper'>

                    <div className='title'>{postObject.title}</div>
                    <div className='text'>{postObject.postText}</div>
                    <div className='username'>{postObject.username}</div>
                </div>


            </div>
            <div className='right__side'>
                <div className='right__side__wrapper'>
                    <div className='add__comment__container'>

                        <input type="text"
                            value={newComment}
                            placeholder="Comment"
                            //  autoComplete="off"
                            onChange={(e) => setNewComment(e.target.value)}

                        />
                        <button onClick={addComment}> Submit Comment</button>

                    </div>
                    <div className='listOfCommnets'>

                        {comments.map((item, index) => {
                            {/* console.log(item, 'item') */ }
                            return <div className='comments' key={index}>Comments:<br />{item.commentBody}</div>

                        })}
                    </div>
                </div>
            </div>

        </div>
    )
}

export default Post

AuthMiddleware.js (Getting the header or requesting header from front-end)

const { verify } = require("jsonwebtoken")


const validateToken = (res, req, next) => {

    console.log(req, 'req')

    console.log(req.header('host'), 'req host')
}

module.exports = { validateToken }

CodePudding user response:

Express doesn't have any req.header(). You will have to use req.get(field) as specified in the express documentation. Checkout express documentation - http://expressjs.com/en/api.html#req.get

CodePudding user response:

If this is Express I don't think there is req.header('host') method, try req.get('host').
See Express docs: https://expressjs.com/en/api.html#req.get

  • Related