节点js无法读取null的属性'headers'

问题描述 投票:0回答:1

我正在尝试使用nodejs,axios,sql通过前端将数据输入到后端服务器中,并且遇到了以下错误:TypeError:无法读取null的属性“ headers”。自从我放入isLoggedinMiddleware以来,我一直在面对这个问题。任何意见,将不胜感激!!祝你有美好的一天

这是前端

 const baseUrl = "http://localhost:3000";
    const loggedInUserID = parseInt(localStorage.getItem("loggedInUserID"));
    const token = localStorage.getItem("token")
    console.log(token)

    if(token === null || isNaN(loggedInUserID)){
        window.location.href = "/login/"
    }else{

        $('#logoff').click(function(){
        event.preventDefault();
        localStorage.removeItem('token')
        localStorage.removeItem('loggedInUserID')
        window.alert('Logging out now')
        window.location.href = "/login/"
        })
             $(document).ready(function () {            
            $('#submitbtn').click((event) => {
                const loggedInUserID = parseInt(localStorage.getItem("loggedInUserID"));
                middleware =  {headers:{'Authorization':'Bearer '+token},data:{id: loggedInUserID}}

                event.preventDefault();
                const itemName = $("#itemName").val();
                const itemDescription = $("#itemDescription").val();
                const price = $('#price').val();
                const image = $('#image').val();
                const requestBody = {
                    itemName: itemName,
                    itemDescription: itemDescription,
                    price: price,
                    fk_poster_id: loggedInUserID,
                    imageUrl: image
                }
                console.log(requestBody);
                axios.post(`${baseUrl}/listings/`, requestBody,middleware)
                    .then((response) => {
                        window.alert("successfully Created")
                    })
                    .catch((error) => {
                        window.alert("Error")
                        console.log(requestBody)

                    })
            })
        })  

    }

isLoggedinMiddleware

const jwt = require("jsonwebtoken");
const JWT_SECRET = process.env.JWT_SECRET;

module.exports = (req, res, next) => {
  const authHeader = req.headers.authorization;
  if (authHeader === null || authHeader === undefined || !authHeader.startsWith("Bearer ")) {
    res.status(401).send();
    return;
  }
  const token = authHeader.replace("Bearer ", "");
  jwt.verify(token, JWT_SECRET, { algorithms: ["HS256"] }, (error, decodedToken) => {
    if (error) {
      res.status(401).send();
      return;
    }
    req.decodedToken = decodedToken;
    next();
  });
};

这是发布的api

app.post("/listings/",(req,res,next)=>{
  listings.insert(req.body,isLoggedInMiddleware,(error,result)=>{
    if(error){
      console.log(error)
      console.log(req.body)
      console.log(isLoggedInMiddleware)
      res.status(500).send('Internal Server Error')
      return;
    }
    console.log(result)
    res.status(201).send({"Listing Id":result.insertId})
  })
})
mysql node.js axios
1个回答
0
投票

尝试

app.post('/listings', isLoggedInMiddleware, (req, res/*, whitout next*/) => ...

also

axois.post(url, { headers: ... }, requestData)
© www.soinside.com 2019 - 2024. All rights reserved.