无法访问node.js服务器中的请求标头



这是关于我的最后一个问题- JsonWebTokenError: jwt必须是一个字符串,node.js

我试图得到简单的
console.log(req.header('host'),'req host')
但是获取整个头对象,就像我将在
console.log(req),'req').

为什么我不能访问头对象的值,我也做了Cors设置,以避免自定义头访问,仍然没有成功?

post .js(发送post请求的报头)

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(从前端获取报头或请求报头)

const { verify } = require("jsonwebtoken")

const validateToken = (res, req, next) => {
console.log(req, 'req')
console.log(req.header('host'), 'req host')
}
module.exports = { validateToken }

Express没有任何req.header()。您必须使用明示文件中指定的req.get(field)。Checkout express文档- http://expressjs.com/en/api.html#req.get

如果这是Express,我不认为有req.header('host')方法,试试req.get('host')
参见Express docs: https://expressjs.com/en/api.html#req.get

相关内容

  • 没有找到相关文章

最新更新