【问题标题】:Axios POST to express api gives Request failedaxios POST 表达 api 给 Request failed
【发布时间】:2019-10-19 19:55:10
【问题描述】:

我正在尝试使用 axios 从我的 React 本机应用程序中发布帖子。这是我写的 express api 的帖子。我尝试发送的数据是正确的,但我不断收到 400 错误请求失败。

我的带有 axios 请求的 React Native 代码是这样的:

postToDatabase = async() => {
    console.log(this.state);
    API.post('/restaurants', {
        name: this.state.name,
        description: this.state.description,
        places_free: this.state.places_free,
        latitude: this.state.latitude,
        longitude: this.state.longitude,
        phone: this.state.phone,
        website: this.state.website
    })
    .then(res => console.log(res))
    .catch(err => console.log(err));
}

快递是这样的:

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

app.post('/api/restaurants', (req, res, next) => {
    var errors = [];
    if(!req.query.name){
        errors.push("No name specified");
    }
    if(!req.query.description){
        errors.push("No description specified");
    }
    if(!req.query.places_free){
        errors.push("No description specified");
    }
    if(!req.query.latitude){
        errors.push("No latitude specified");
    }
    if(!req.query.longitude){
        errors.push("No longitude specified");
    }
    if(!req.query.phone){
        errors.push("No phone specified");
    }
    if(!req.query.website){
        errors.push("No website specified");
    }

    if(errors.length){
        res.status(400).json({"error": errors.join(',')});
        return;
    }

    var data = {
        name: req.body.name,
        description: req.body.description,
        places_free: req.body.places_free,
        latitude: req.body.latitude,
        longitude: req.body.longitude,
        phone: req.body.phone,
        website: req.body.website
    }

    var sql = "INSERT INTO restaurants (name, description, places_free, latitude, longitude, phone, website) VALUES (?, ?, ?, ?, ?, ?, ?)";
    var params = [data.name, data.description, data.places_free, data.latitude, data.longitude, data.phone, data.website];
    db.run(sql, params, (err, result) => {
        if(err){
            res.status(400).json({"error": err.message});
            return;
        } else {
            res.json({
                "status" : "succes",
                "data": data
            });
        }
    });
});

我希望有人能看出我哪里弄错了。

【问题讨论】:

    标签: node.js react-native post axios


    【解决方案1】:

    可能还有其他错误,但我发现的一个错误是您使用req.query,而您应该使用req.body

    req.query 用于查询参数,如/api/example?foo=bar,而req.body 用于请求正文

    【讨论】:

    • 你的意思是在错误检查中?我会尝试删除它们,看看它是否有效。
    • 是的,因为在您的请求中,不会填充 req.query,但会填充 req.body
    • 解决了问题,其余代码按预期运行,插入发生了。将重写错误检查以使用 req.body
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-20
    • 2015-06-02
    • 2019-10-22
    • 2020-04-17
    • 1970-01-01
    • 2022-10-19
    相关资源
    最近更新 更多