【问题标题】:Query using http post request使用http post请求查询
【发布时间】:2020-08-16 23:27:49
【问题描述】:

当我使用 app.get 作为 localhost:3000/data?country=Italy 在 url 中查询时,我将数据存储在 MongoDb 中。如何使用 app.post 请求方法查询参数并获取数据?我找不到合适的解决方案,而且我对此完全陌生。

const express = require("express");
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const url = "mongodb://localhost:27017/source_scrapped_data";
const app = express();
mongoose.connect(url, { useNewUrlParser: true });
// mongoose.Promise = global.Promise;
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', () => {
    console.log("Connected to mongo");
});
const covid_data = mongoose.model('Covid',
    new Schema({}),
    'covid_data');
app.get("/data", (req, res) => {
    const continent = req.query.continent;
    const country = req.query.country;
    covid_data.find({'Continent':continent,'Country':country},(err,docs)=>{
        if(err){
            console.log(err)
            res.send("no data found",err)
        }
        else{
            console.log(err)
            res.send(docs)
        }
    });
});
module.exports = app;

【问题讨论】:

  • POSTt 用于向服务器发送数据,而GET 用于从服务器获取数据。因此,从服务器返回时使用 GET 请求而不是 POST

标签: node.js mongodb api express mongoose


【解决方案1】:
app.post("/data", (req, res) => {
    const continent = req.body.continent;
    const country = req.body.country;
    covid_data.find({'Continent':continent,'Country':country},(err,docs)=>{
        if(err){
            console.log(err)
            res.send("no data found",err)
        }
        else{
            console.log(err)
            res.send(docs)
        }
    });
});

这是您可以在请求正文中传递的发布请求中获取数据的方式。

  • 这不是您不应该使用发布请求来获取查询的标准做法。始终使用 POST 方法将一些数据放入数据库中。

【讨论】:

  • 在运行 url: localhost:3000/data?country=India 时无法 GET /post_data...而不是给我完整的数据...请您指导我... .im 只是为了学习如何使用 post ...将是一个非常大的帮助
  • 可以使用postman等工具来测试api。因为我认为您正在尝试使用发布数据获取请求。
猜你喜欢
  • 1970-01-01
  • 2021-06-02
  • 1970-01-01
  • 2020-07-14
  • 1970-01-01
  • 1970-01-01
  • 2017-11-28
  • 2011-04-10
  • 2013-06-14
相关资源
最近更新 更多