【问题标题】:Cache/save to db a Json Body from a GET request从 GET 请求缓存/保存到 db Json Body
【发布时间】:2016-10-04 21:44:23
【问题描述】:

在了解了如何使用 node.js 和平均堆栈的基础知识之后,我喜欢从我自己的项目开始。

问题是:
我无法访问请求的 API 的 json 正文/属性,我喜欢将其保存到 mongodb 并每 24 小时自动更新一次。

我正在尝试什么:
是调用 2 个 API。这些响应与我尝试以相同名称合并到我的猫鼬模式中的数据集的 json 列表。使用 body.param 或 response.param,没用。

获取请求的示例响应:
url1/api/products/all

{
 data: [
  {
  id: 1,
    product_name: "Product1",
    app: appName,
    quantity: 137360,
    price: 0.05,
    updated_at: "2016-06-04 23:02:03",
    median_week: 0.04,
    median_month: 0.05,
  },
  .....
  {
    id:142640
    ...
  }   
}  

url2/api/item/all?key=apikey

{
  success: true,
  num_items: 6713,
  products: [
            {
             product_name: "Product1",
             ....
             icon_url: "//url/economy/image/bla.png",
             product_color: "8650AC",
             quality_color: "EB4B4B"
             },
             ....

在发现只表示到本地 url 的路由后,我现在使用请求。
那是我的路由/item.js

var express = require('express');
var qs = require('querystring');
var request = require('request');
var _ = require('underscore');
var router = express.Router();
var Item = require('../models/item');



var options = {
    url:  'url2' + ?key + app.config.url2.apikey ,
    port: 80,
    method: 'GET',
    json:true
}

/* GET listing. */
router.get('/', function(req, res) {
  request.get('url', function (error, response, body) {

  if (!error && response.statusCode == 200) {
      console.log(body) // Prints JSON Body
   //Iterate through each id of url1 and num_items of url2 and update collection
   // Better to make another request method just to call the second api?
    for each(item in body.id || body.num_items) {

    var newItem = Item({
      id: item[i],
      product_name: ,

      app: 'appName',
      quantity: res.body.quantity,
      price: res.body.price,
      ....
      icon_url: res.body.,
      name_color: res.body.,
      quality_color: body.,
      created_at: Date.now,
      updated_at:

      })

      newItem.save(function(err) {
        if (err) throw err;

      console.log('Item created');
      })
      //return res.json(body); 
    }
   }
   res.sendStatus('304');
  });

});

这是我的物品模型

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var ItemSchema = new Schema({
  id: String,
  ....      
  created_at: {
    type: Date,
    default: Date.now
  },
  updated_at: Date
});


var Item = mongoose.model('Item', ItemSchema);

  ItemSchema.pre('save', function(next) {

   var currentDate = new Date();
   this.updated_at = currentDate;

   if (!this.created_at)
    this.created_at = currentDate;

  next();
});

module.exports = Item;

写完这个问题后,我认为这不是解决这个问题的最佳方法。有什么最佳做法吗?

【问题讨论】:

  • 你有几个问题:res.body必须是req.body,你必须异步遍历数组(使用async包),保存所有数据后发送结果

标签: javascript node.js mongodb express mongoose


【解决方案1】:

你有几个问题:

  1. res.body 必须是 req.body
  2. 您必须异步迭代数组(使用异步包)
  3. 保存所有数据后发送结果

请看下面的示例

router.get('/', function(req, res) {

    // npm install async --save
    var async = require('async');
    request.get('url', function (error, response, body) {
        if (error && response.statusCode !== 200) {

            // request could not be completed
            return res.send(400, {message: 'Something went wrong'});
        } else {

            // get the count
            var iterator = body.id || body.num_items;

            // iterate number of times
            async.times(iterator, function(number, next){

                // create your new object
                var newItem = Item({
                    id: number,
                    product_name: ,
                    app: 'appName',
                    quantity: req.body.quantity, // <== not res.body
                    price: req.body.price,
                    icon_url: req.body.,
                    name_color: req.body.,
                    quality_color: body.,
                    created_at: Date.now
                });

                // save and call next (which is callback)
                newItem.save(next);
            }, function(timesErr, timesResult){

                // if something failed, return error
                // even if 1 item failed to save, it will return error
                if(timesErr) {
                    return res.send(400, {message: 'Something went wrong'});
                }
                // send the list of saved items;
                // or whatever you want
                res.status(200).send(timesResult);
            });
        }
    });
});

【讨论】:

  • 感谢您,我尝试记录所有可以帮助我接收这些身体参数的内容,但所有内容都未定义。我在这之前使用了 req.body,这就是我最后的原因。即使我有 body-parser 作为依赖项。这是一个输出示例{ __v: 0, id: "0", appid: 730, updated_at: "2016-06-05T16:18:49.445Z", _id: "575450e9a3ad44e02a08615c", created_at: "2016-06-05T16:18:49.408Z" }, { __v: 0, id: "1", appid: 730, updated_at: "2016-06-05T16:18:49.469Z", _id: "575450e9a3ad44e02a08615d", created_at: "2016-06-05T16:18:49.430Z" } 如您所见,我无法访问 json 正文中的数据
  • 这是另一个问题,打开新问题,因为这不适合当前发布您提供的问题
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-04-20
  • 2018-07-25
  • 2015-01-12
  • 1970-01-01
  • 2017-12-10
  • 2013-12-12
  • 1970-01-01
相关资源
最近更新 更多