javascript - axios 数据正在破坏请求

标签 javascript node.js reactjs express axios

我有一个 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)

我的 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}`);
});

有什么想法吗?谢谢。

更新

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

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

但是我的 console.log 没有显示我使用有效载荷(当我不使用时)。

最佳答案

您应该通过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

在您的 express 端点 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'
  })

在您的 express 端点 request.body 将是:

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

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

关于javascript - axios 数据正在破坏请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54424802/

相关文章:

javascript - Mongoose 与 Supertest 的开放连接问题

node.js - 集成测试 node.js socket.io 服务器

reactjs - 如何使用react-router-redux的routeActions?

javascript - tweenMax.to 在 React componentDidMount 中不起作用

javascript - 如何使用模板从另一个 IIFE 访问一个 IIFE 内的变量?

javascript - react native 相机胶卷 "null is not an object (evaluating ' this.state.photos')"

javascript - 使用 RegExp 屏蔽字符串的一部分

javascript - 使用 NPM install 从文件安装 NodeJS 包

reactjs - Firebase 云函数压缩视频

javascript - 如何将 sprite 表图像缩放到容器?