简体   繁体   English

没有从 axios 请求读取到 nodejs 服务器的 json 数据

[英]no json data read from axios request to nodejs server

I have a signup page where the user is required to confirm their password.我有一个注册页面,用户需要在其中确认密码。 For this, I have created the following axios and server side code to handle the request.为此,我创建了以下axios和服务器端代码来处理请求。

TL;DR using suggested methods found here , and here , and here , I send an axios request with the format: TL;DR 使用此处此处和此处找到的建议方法,我发送了一个axios请求,格式如下:

axios({
    method: 'get',
    url: '/my/server/endpoint',
    data: *json data*
});

and on my nodejs (express) server, I listen for req.body (suggested here , here , here , here ) content or req.data (suggested here , here ).在我的nodejs(express)服务器上,我监听req.body (建议herehereherehere )内容或req.data (建议herehere )。

Problem:问题:

Simply said, req.body is an empty object and req.data is undefined (see image below).简单地说, req.body是一个空的 object 并且req.data是未定义的(见下图)。

I have the following express app setup我有以下快速app设置

const app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');

app.use(logger('dev'));
app.use(express.json());
app.use(helmet());
app.use(express.urlencoded({extended: false}));
app.use(cookieParser());
app.use('/assets', express.static(path.join(__dirname, '/assets')));
app.use(cors());
app.use(session({secret: config.secret, resave: false, saveUninitialized: false}));
app.use(passport.initialize({}));
app.use(passport.session({secret: config.secret}));
app.use(function(req,res,next){
    res.locals.session = req.session;
    next();
});
app.use(flash());

I can confirm the data sent via the axios request does infact have valid data being sent.我可以确认通过axios请求发送的数据确实发送了有效数据。

Did I do something wrong?我做错什么了吗?

在此处输入图像描述

Client Side Code客户端代码

$('#btnSetVaultPassword').click(function () {
    $('#btnSetVaultPassword').prop("disabled", true);

    let password = $('#edtVaultPassword');
    let passwordConfirm = $('#edtVaultPasswordConfirm');

    // const data = ;

    axios({
        method: 'get',
        url: '/setup/setup-vault',
        data: {
            password: password.val(),
            passwordConfirm: passwordConfirm.val()
        }
    }).then((result) => {
        if(result.status === true) {
            // set success alert with message
            let alertMessage = document.createElement("div");
            alertMessage.classList.add("alert", "alert-success");
            alert.val(result.message);
            $('.container-fluid').prepend(alertMessage);

            // hide modal
            $('#dialogVault').modal({show: false});

        } else {
            // show message on modal
            $('#vaultMessage').val(result.message);

            // enable setVaultPassword button
            $('#btnSetVaultPassword').prop("disabled", false);
        }
    });
});

Corresponding NodeJS (Express) Server Side code对应的NodeJS(Express)服务端代码

router.get('/setup-vault',
    async function (req, res, next) {
        let pass = req.body.password;
        let confirmPass = req.body.passwordConfirm;

        if(pass === undefined || pass === "" ||
            confirmPass === undefined || confirmPass === "") {
            res.json({status: false, message: "Password(s) cannot be empty"});
        }

        if(pass !== confirmPass) {
            res.json({status: false, message: "Keys don't match"});
        } else {
            const vaultHash = vault.encrypt(pass, Buffer.from(settingName.vaultSecret));
            await createOrSaveSetting(settingName.vaultSecret, vaultHash);
            // test connection
            res.json({status: true, message: "Vault created"});
        }
    });

I think you have to use a POST method to get data in the body section, if you are using GET, like it's in you code now, you can only get the parameters via URL query strings, you had to do it like this with POST, for you code to work:我认为您必须使用 POST 方法来获取正文部分中的数据,如果您使用的是 GET,就像现在在您的代码中一样,您只能通过 URL 查询字符串获取参数,您必须使用 POST 这样做,让你的代码工作:

Client-Side客户端

$('#btnSetVaultPassword').click(function () {
    $('#btnSetVaultPassword').prop("disabled", true);

    let password = $('#edtVaultPassword');
    let passwordConfirm = $('#edtVaultPasswordConfirm');

    // const data = ;

    axios({
        method: 'post',
        url: '/setup/setup-vault',
        data: {
            password: password.val(),
            passwordConfirm: passwordConfirm.val()
        }
    }).then((result) => {
        if(result.status === true) {
            // set success alert with message
            let alertMessage = document.createElement("div");
            alertMessage.classList.add("alert", "alert-success");
            alert.val(result.message);
            $('.container-fluid').prepend(alertMessage);

            // hide modal
            $('#dialogVault').modal({show: false});

        } else {
            // show message on modal
            $('#vaultMessage').val(result.message);

            // enable setVaultPassword button
            $('#btnSetVaultPassword').prop("disabled", false);
        }
    });
});

and the Server-Side:和服务器端:

router.post('/setup-vault',
    async function (req, res, next) {
        let pass = req.body.password;
        let confirmPass = req.body.passwordConfirm;

        if(pass === undefined || pass === "" ||
            confirmPass === undefined || confirmPass === "") {
            res.json({status: false, message: "Password(s) cannot be empty"});
        }

        if(pass !== confirmPass) {
            res.json({status: false, message: "Keys don't match"});
        } else {
            const vaultHash = vault.encrypt(pass, Buffer.from(settingName.vaultSecret));
            await createOrSaveSetting(settingName.vaultSecret, vaultHash);
            // test connection
            res.json({status: true, message: "Vault created"});
        }
    });

If you intend to use the GET method you should use the query string option in the server side, and change the client-side to use params in the place of data in your Axios request.如果您打算使用 GET 方法,则应在服务器端使用查询字符串选项,并更改客户端以使用参数代替 Axios 请求中的数据

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM