You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Express应用调用创建订单API遇400错误求助(附Axios代码)

调用labelsupply.io创建订单API返回400错误的排查与修复

问题场景

在Express应用中,从EJS表单获取req.body数据后,通过Axios调用labelsupply.io的创建订单API,始终返回400错误。已通过console.log确认req.body数据正常,相关代码如下:

app.post('/order-labels', checkAuthenticated, (req, res) => {
    const data = JSON.stringify(req.body);
    console.log(data)
    const config = {
        method: 'post',
        url: 'https://labelsupply.io/api/order',
        headers: {
            'X-Api-Auth': '32854090-03dd-a3c1-Deleted some for safety',
            'Content-Type': 'application/x-www-form-urlencoded'
        },
        data: data
    };

    axios(config)
        .then(function(response) {
            console.log(response.data);
        })
        .catch(function(error) {
            console.log(error);
        });
})

核心问题与修复方案

  • Content-Type与数据格式不匹配:你设置了Content-Type: application/x-www-form-urlencoded,但实际传递的是JSON字符串(JSON.stringify(req.body)),服务端无法解析这种格式的请求,因此返回400错误。

修复方式1:使用表单编码格式传递数据

借助qs库将req.body对象转为表单编码格式(需先安装qs:npm install qs):

const qs = require('qs');

app.post('/order-labels', checkAuthenticated, (req, res) => {
    const data = qs.stringify(req.body);
    console.log(data)
    const config = {
        method: 'post',
        url: 'https://labelsupply.io/api/order',
        headers: {
            'X-Api-Auth': '32854090-03dd-a3c1-Deleted some for safety',
            'Content-Type': 'application/x-www-form-urlencoded'
        },
        data: data
    };

    axios(config)
        .then(function(response) {
            console.log(response.data);
        })
        .catch(function(error) {
            console.log(error.response?.data || error.message);
        });
})

修复方式2:改用JSON格式传递数据

若API支持JSON格式(可查看官方文档确认),修改Content-Type为application/json,直接传递req.body对象即可(Axios会自动将对象序列化为JSON):

app.post('/order-labels', checkAuthenticated, (req, res) => {
    console.log(req.body)
    const config = {
        method: 'post',
        url: 'https://labelsupply.io/api/order',
        headers: {
            'X-Api-Auth': '32854090-03dd-a3c1-Deleted some for safety',
            'Content-Type': 'application/json'
        },
        data: req.body
    };

    axios(config)
        .then(function(response) {
            console.log(response.data);
        })
        .catch(function(error) {
            console.log(error.response?.data || error.message);
        });
})

额外排查点

  • 核对API文档,确认所有必填字段是否齐全、字段名是否拼写正确
  • 验证X-Api-Auth令牌的有效性,部分场景下令牌无效也会返回400错误
  • 在catch回调中打印error.response.data,获取服务端返回的具体错误提示,精准定位问题

内容的提问来源于stack exchange,提问作者Jason Arendt

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 11:48:24