【问题标题】:Axios data is breaking the requestaxios 数据中断请求
【发布时间】:2019-06-22 19:14:58
【问题描述】:

我有一个express API 和一个ReactJs 前端。我尝试从前端直接向本地 API 发起 POST 调用。

为此,我使用axios

当我直接在查询字符串中设置参数时,请求工作正常,但如果我尝试通过axios.post() 方法的data 属性添加参数,则总是超时。

工作

axios.post(`http://localhost:5001/site/authenticate?username=demo&password=demo`)

不工作

const payload = {
    "username":"mh",
    "password":"mh"
}
axios.post(`http://localhost:5001/site/authenticate`, payload)

我的快递服务器:

const express = require('express');
const bodyParser = require('body-parser');
const morgan = require('morgan');
const jwt = require('jsonwebtoken'); // used to create, sign, and verify tokens
var cors = require('cors');

const app = express();
const port = process.env.API_PORT || 5001;

app.use(cors());
app.set('secret', process.env.API_SECRET);

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

app.use(morgan('dev'));

app.use((req, res, next) => {
    let data = '';
    req.setEncoding('utf8');
    req.on('data', (chunk) => {
        data += chunk;
    });
    req.on('end', () => {
        req.rawBody = data;
        next();
    });
});

// Allow CORS
app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});

// SITE ROUTES -------------------
const siteRoutes = express.Router(); 

siteRoutes.post('/authenticate', function(req, res) {
    console.log('auth');
    getDocument(usersBucket, req.query.username)
        .then((doc) => {
            console.log("Authentification... TODO");

            // return the information including token as JSON
            res.json({
                success: true,
                status: 200,
                token: token
            });
        })
        .catch(() => {
            res.status(401).json({ success: false, message: 'Authentification failed. User not found.' });
        });
});

// route middleware to verify a token
siteRoutes.use(function(req, res, next) {
    const token = req.body.token || req.query.token || req.headers['x-access-token'];

    if (token) {
    // verifies secret and checks exp
    jwt.verify(token, app.get('secret'), function(err, decoded) {
            if (err) {
                return res.json({ success: false, message: 'Failed to authenticate token.', status: 401 });       
            } else {
                req.decoded = decoded;
                next();
            }
    });

  } else {
    return res.status(403).send({ 
        success: false, 
        message: 'No token provided.' 
    });
  }
});

siteRoutes.get('/', function(req, res) {
  res.json({ message: 'Welcome!' });
});

app.use('/site', siteRoutes);

app.listen(port, () => {
    logger.log(`Express server listening on port ${port}`);
});

有什么想法吗?谢谢。

更新

我替换了我的路线只是为了看看我是否进入(不用担心参数):

siteRoutes.post('/authenticate', function(req, res) {
    console.log("go in");
    res.json({
        success: true,
        status: 200,
    });
});

但是我的console.log 没有显示我使用有效负载的情况(这是我不使用的时候)。

【问题讨论】:

    标签: javascript node.js reactjs express axios


    【解决方案1】:

    您应该通过request.body 访问payload 数据,而不是request.query

    // SITE ROUTES -------------------
    const siteRoutes = express.Router(); 
    
    siteRoutes.post('/authenticate', function(req, res) {
        console.log('auth');
        getDocument(usersBucket, req.body.username) // <------- HERE
            .then((doc) => {
                console.log("Authentification... TODO");
    
                // return the information including token as JSON
                res.json({
                    success: true,
                    status: 200,
                    token: token
                });
            })
            .catch(() => {
                res.status(401).json({ success: false, message: 'Authentification failed. User not found.' });
            });
    });
    

    request.query是URL中传递的参数,如:

    protocol://hostname:port/path/to.route?query_param_0=value_0&query_param_1=value_1
    

    在您的快速端点上request.query 将是:

    { 
      query_param_0: value_0,
      query_param_1: value_1
    }
    

    在发送payload 时,使用second argument in axios.post(url, payload)

    axios.post('/user', {
        firstName: 'Fred',
        lastName: 'Flintstone'
      })
    

    在您的快速端点上request.body 将是:

    {
      firstName: 'Fred',
      lastName: 'Flintstone'
    }
    

    当你使用 app.use(bodyParser.json()); 时(你确实这样做了)。

    【讨论】:

    • 谢谢,其实我应该用req.body,但我不认为这是问题的根源。正如您在我的问题更新中看到的那样,在使用有效负载时,我的请求甚至没有进入我的快速路由。有什么想法吗?
    【解决方案2】:

    您正在使用“getDocument(usersBucket, req.query.username)”

    这意味着您表达的路线期望用户名作为请求参数。这就是为什么当你使用“?username=xx”时它会起作用

    而是尝试从请求的 json 正文中获取它。 “req.body.username”

    您还应该考虑根据需要验证请求正文或参数。

    【讨论】:

    • “根据需要验证请求正文或参数”是什么意思?我没有复制检查用户是否存在于数据库中以及哈希密码的函数,因为我认为它与我的问题无关。
    猜你喜欢
    • 2017-12-12
    • 2023-03-27
    • 2018-06-29
    • 2018-02-01
    • 2020-02-02
    • 2021-08-11
    • 2019-11-22
    • 1970-01-01
    • 2022-11-29
    相关资源
    最近更新 更多