Javascript Axios数据正在中断请求

Javascript Axios数据正在中断请求,javascript,node.js,reactjs,express,axios,Javascript,Node.js,Reactjs,Express,Axios,我有一个API和一个前端。我尝试从前端直接对本地API进行POST调用 我用这个 当我直接在查询字符串中设置参数时,请求工作正常,但如果我试图通过axios.post()的data属性添加参数,请求总是超时 工作 axios.post(`http://localhost:5001/site/authenticate?username=demo&password=demo`) const payload = { "username":"mh", "password":"m

我有一个API和一个前端。我尝试从前端直接对本地API进行POST调用

我用这个

当我直接在查询字符串中设置参数时,请求工作正常,但如果我试图通过
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)
不工作

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)
我的express服务器:

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}`);
});
有什么想法吗?谢谢

更新 我更换了路线,只是想看看我是否进入(不必担心参数):


但是当我使用有效负载时,我的
控制台.log
不显示(当我不使用有效负载时显示)。

您应该通过
请求.body
访问
有效负载
数据,而不是
请求.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.' });
        });
});
在您的express endpoint
请求中。查询将是:

{ 
  query_param_0: value_0,
  query_param_1: value_1
}
{
  firstName: 'Fred',
  lastName: 'Flintstone'
}
发送
有效负载时,使用:

在您的express endpoint
请求中。正文将是:

{ 
  query_param_0: value_0,
  query_param_1: value_1
}
{
  firstName: 'Fred',
  lastName: 'Flintstone'
}

当您使用app.use(bodyParser.json())时(您确实如此)。

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

这意味着您的express route需要用户名作为请求参数。这就是为什么使用“?username=xx”时它会工作的原因

相反,尝试从请求的json主体获取它。 “请求正文用户名”


您也应该根据需要验证请求体或参数。

您的意思是“根据需要验证请求体或参数”?我没有复制用于检查数据库中是否存在用户以及哈希密码的函数,因为我认为它与我的问题无关。谢谢,事实上我应该使用
req.body
,但我不认为这是问题的根源。正如您在我的问题更新中所看到的,在使用有效负载时,我的请求甚至没有进入我的快速路线。有什么想法吗?