我必须在节点 js 中创建一个 api 我将它创建为 curl 如何将 cURL 请求转换为节点 js。如何在节点 js 中传递 url、header 和 data 二进制文件?以下是 cURL 请求?
curl -v "https://us-extract.api.smartystreets.com/?auth-id=AUTH_ID&auth-token=AUTH_TOKEN" -H "content-type: application/json" --data-binary ""
我必须在节点 js 中创建一个 api 我将它创建为 curl 如何将 cURL 请求转换为节点 js。如何在节点 js 中传递 url、header 和 data 二进制文件?以下是 cURL 请求?
curl -v "https://us-extract.api.smartystreets.com/?auth-id=AUTH_ID&auth-token=AUTH_TOKEN" -H "content-type: application/json" --data-binary ""
有一些非常方便的工具,请查看https://curl.trillworks.com/#node,它将 curl 请求转换为 Node.js、Python、Go 等中的代码。
我已将您的 curl 请求稍微更改为:
curl -v -X POST "https://us-extract.api.smartystreets.com/?auth-id=AUTH_ID&auth-token=AUTH_TOKEN" -H "content-type: application/json" --data-binary "1600 Amphitheatre Parkway,Mountain View, CA 94043"
(注意我已经修改了你的 auth-id 和 auth-token,我们不让其他人使用这些.. :-))
在您的示例中,输出将如下所示,请注意这使用请求库。您必须执行 npm install 请求才能将其添加到您的项目中。
var request = require('request');
// Put your auth id and token here.
const AUTH_ID = "";
const AUTH_TOKEN = "";
var headers = {
'content-type': 'application/json'
};
var dataString = '1600 Amphitheatre Parkway,Mountain View, CA 94043';
var options = {
url: 'https://us-extract.api.smartystreets.com/?auth-id=' + AUTH_ID + '&auth-token=' + AUTH_TOKEN,
method: 'POST',
headers: headers,
body: dataString,
json: true // Set this to parse the response to an object.
};
function callback(error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body);
// Log the API output.
(body.addresses || []).forEach((element, index) => {
console.log(`api_output (address #${index+1}):`, element.api_output);
});
}
}
request(options, callback);