簡體   English   中英

如何在我的 axios post 請求中正確添加標頭,post 路由在 postman 中有效,但在使用 axios 時無效

[英]How can I properly add headers in my axios post request, post route works in postman but not when using axios

我正在嘗試使用 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 請求呢? 提前致謝。

從這一行我可以看到您正在檢查名為JWT的標頭。

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

但是在 axios 中,您發送的是Authorization標頭:

{ headers: { Authorization: `JWT ${accessString}` }

您需要發送JWT標頭。 或者,如果您想檢查Authorization標頭,只需檢查一下:

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

此外,只需發送<token> ,如果您發送JWT <token>那么您需要拆分標頭並僅檢查<token>部分。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM