[英]Inserting Value in API with HTTP-Request
我正在使用Package 请求 。 您可以在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)
}
});
}
希望你们能提供帮助,我现在真的很难过。
最好的祝福
麦可
传递给request
功能的选项中存在问题。 请在此处参阅请求文档 。
请参见下面的代码。 我对通过的选项进行了更改。 这会起作用。
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
函数的第二个参数。
注意
请注意, 更新myjson api只会将现有数据替换为您提供的新数据。 它不会追加数据。 如果要附加数据,首先需要获取数据,然后将其与新数据合并并使用API更新。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.