【问题标题】:request body empty with POST node js ajax calling with json web token请求正文为空,POST 节点 js ajax 调用 json Web 令牌
【发布时间】:2020-08-30 17:15:24
【问题描述】:

你能帮帮我吗~

我正在尝试在节点 js 上使用 json webtoken 并调用 post 方法来设置数据。

节点js服务器上的代码:

app.use(bodyParser.raw({ type: 'application/jwt' }));

代码前端调用:

$.ajax({
            url: '/setSession',
            type: 'POST',
            Accept : 'application/json',
            //contentType: 'application/json',
            dataType: 'json',
            data: { "hello": templateName}, 
            //data: JSON.stringify({ "hello": templateName}), 
            headers: {
               'Authorization': 'Bearer '+ token
            },
            success: function (result) {console.log('post ok'+JSON.stringify(result));
                // CallBack(result);
            },
            error: function (error) { console.log('post failed'+JSON.stringify(error));
         
            }
         });

但是调用post请求时req.body为空或者{},我尝试了bodyparser,或者dataType但是没有成功

【问题讨论】:

    标签: jquery node.js post jwt


    【解决方案1】:

    1) 对于您的服务器代码,应该如何实现:

    const express = require('express');
    const bodyParser = require('body-parser');
    const jwt = require('jsonwebtoken');
    
    const app = express();
    
    app.use(bodyParser.json());
    
    app.listen(4000, () => {
        console.log('Books service started on port 4000');
    });
    

    2) 你必须定义一个中间件来检查它是否是一个有效的令牌:

    const authenticateJWT = (req, res, next) => {
        const authHeader = req.headers.authorization;
    
        if (authHeader) {
            const token = authHeader.split(' ')[1];
    
            jwt.verify(token, accessTokenSecret, (err, user) => {
                if (err) {
                    return res.sendStatus(403);
                }
    
                req.user = user;
                next();
            });
        } else {
            res.sendStatus(401);
        }
    };
    

    3) 后置路由器:

    app.post('/setSession', authenticateJWT, (req, res) => {
       /* your logic here */
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-04-04
      • 2018-11-28
      • 2017-08-19
      • 2019-01-28
      • 2012-04-11
      • 2016-02-11
      • 1970-01-01
      相关资源
      最近更新 更多