【问题标题】:Inserting Value in API with HTTP-Request使用 HTTP-Request 在 API 中插入值
【发布时间】:2018-06-19 04:01:43
【问题描述】:

我正在使用包请求。你可以在 npm 中找到它。我多次尝试在我的 API 中添加数据。我的 API 来自 myjson.com/api。我真的需要帮助。我尝试了所有方法,例如 put,post,get ...。我只想将客户添加到 API 中。每次如果对象客户的值发生变化,它应该创建一个新行并将这个客户添加到。

例如:您有一个客户可以注册的网站。然后您将每次注册都保存在 API 中的新行中。

var customer = {
    "Customerid": customerID,
    "Sex": sex,
    "Lastname": lastname,
    "Firstname": firstname,
    "State": state,
    "Street": street,
    "Postcode": postcode,
    "Birthdate": birthdate,
    "Email": email,
    "Monthly Earnings": mothEarn
};

var customerData = JSON.stringify(customer);
addCustomerAPI(customerData);



function addCustomerAPI(customerData){
   request({
                url: "https://api.myjson.com/bins/1efewz",
                type: "PUT",
                data: customerData,
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (data, textStatus, jqXHR) {
                    console.log(data)
                }
            });


}

希望大家帮忙,我现在真的很难过。

最好的问候

迈克尔

【问题讨论】:

  • 您是否遇到任何错误?
  • 我发布的网页上没有任何内容。它在我运行应用程序后更新值,但在我的应用程序中它不起作用
  • 你在js文件中导入模块了吗? @MichaelDev var request = require('request')
  • 是的,它已经实现了

标签: javascript json api http request


【解决方案1】:

您传递给request 函数的选项存在问题。请参阅此处的request docs

请参阅下面的代码。我对通过的选项进行了更改。这会奏效。

var customer = {
  "Customerid": customerID,
  "Sex": sex,
  "Lastname": lastname,
  "Firstname": firstname,
  "State": state,
  "Street": street,
  "Postcode": postcode,
  "Birthdate": birthdate,
  "Email": email,
  "Monthly Earnings": mothEarn
};

addCustomerAPI(customer);

function addCustomerAPI(customer){
  request({
    url: "https://api.myjson.com/bins/1efewz",
    method: "PUT",
    json: customer
  }, function (err, res, body) {
    console.log(body);
  });


}

customer JSON 可以直接传递,无需转换成字符串,回调函数是request 函数的第二个参数。

注意

请注意,update myjson api 只会将现有数据替换为您提供的新数据。它不会附加数据。如果要追加数据,首先需要获取数据,然后将它们与新数据合并并使用 API 更新。

【讨论】:

  • 合并是指像一个数组一样保存现有数据并添加新数据?
  • @MichaelDev 是的,首先存储在myjson api 上的现有数据将被收集并存储在一个数组中。新数据将附加到这个数组,结果数组将存储到 myjson。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-09-21
  • 1970-01-01
  • 2019-06-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多