如何在我的 axios 发布请求中正确添加标头,发布路由在邮递员中有效,但在使用 axios 时无效

Posted

技术标签:

【中文标题】如何在我的 axios 发布请求中正确添加标头,发布路由在邮递员中有效,但在使用 axios 时无效【英文标题】:How can I properly add headers in my axios post request, post route works in postman but not when using axios 【发布时间】:2020-06-03 20:49:23 【问题描述】:

我正在尝试使用 JWT 来保护我的 nodejs、express、react 应用程序中的 post 路由。 我通过将 JWT 令牌添加到标题中使用邮递员对其进行了测试,并且可以完美地将用户添加到数据库中。但是,如果我使用 axios 从 react 发出请求,我会收到 401 响应(未经授权)。

这是我来自前端的 axios post 请求:

addClient = async e => 

let newUser = 
                businessname: businessname.toLowerCase(),
                firstName: firstName.toLowerCase(),
                lastName: lastName.toLowerCase(),
                email,
                username,
                password,
                phoneNumber,
                customerStatus: customerStatus.value,
                userType,
                Gooduntil
            ;
            const accessString = localStorage.getItem("JWT");
            await Axios.post("/auth/signup", newUser, 
                headers:  Authorization: `JWT $accessString` 
            )
                .then(res => 
                    console.log(res);
                    return this.setState(
                        loadingAxiosReq: false
                    );
                )
                .catch(err => 
                    return console.log(err);
                );

这是我的发帖路线:

router.post("/signup", verifyToken, (req, res) => 
    console.log(req.headers);

    const 
        businessname,
        username,
        firstName,
        lastName,
        phoneNumber,
        email,
        password,
        customerStatus,
        userType,
        Gooduntil
     = req.body;

    if (password.length < 8) 
        throw "Password must be at least 8 characters";
     else 
        User.findOne(
            where: 
                email
            
        ).then(user => 
            if (user) 
                return res.send("Email already exists!");
             else 
                const encryptedPassword = bcrypt.hashSync(password, salt);

                let newUser = 
                    businessname,
                    username,
                    firstName,
                    lastName,
                    phoneNumber,
                    email,
                    password: encryptedPassword,
                    customerStatus,
                    userType,
                    Gooduntil
                ;
                User.create(newUser)
                    .then(() => 
                        // newUser.isAdmin = true
                        delete newUser.password;
                        res.send(newUser);
                    )
                    .catch(function(err) 
                        console.log(err);
                        res.json(err);
                    );
            
        );
    
);

这是我的中间件:

const jwt = require("jsonwebtoken");

module.exports = function(req, res, next) 
    const token = req.header("JWT");
    if (!token) return res.status(401).send("Access Denied!");

    try 
        const verified = jwt.verify(token, process.env.JWT_SECRET);
        req.user = verified;
        return next();
     catch (err) 
        res.status(400).send("Invalid Token!");
    
;

那么,我怎样才能正确地提出我的 axios 请求呢? 提前致谢。

【问题讨论】:

【参考方案1】:

从这一行我可以看到您正在检查一个名为 JWT 的标头。

const token = req.header("JWT");

但在 axios 中,您发送的是 Authorization 标头:

 headers:  Authorization: `JWT $accessString` 

您需要发送JWT 标头。另外,如果您想检查 Authorization 标头,只需检查:

const token = req.headers['authorization'];

另外,只需发送&lt;token&gt;,如果发送JWT &lt;token&gt;,则需要拆分标题并仅检查&lt;token&gt; 部分。

【讨论】:

以上是关于如何在我的 axios 发布请求中正确添加标头,发布路由在邮递员中有效,但在使用 axios 时无效的主要内容,如果未能解决你的问题,请参考以下文章

如何在需要标头的axios发布请求中具有配置参数

如何从使用 axios 发送的 POST 请求中获取 Content-Length 标头?

如何在后端使用 Nuxt 和 Django 在我的 axios 请求中发送 CSRFToken?

IE 11 未在 API 调用中传递授权标头

如何为每个 http 调用中的默认请求标头创建 axios 配置?

Axios 拦截器令牌标头存在于配置中,但不存在于请求标头中