[英]Converting a PHP cURL request into node.js
我正在實現Summry ,並且它們僅提供PHP API連接示例-有人可以將其轉換為JS請求嗎?
我本質上只是希望它解析我給它的文本,還沒有什么特別的。
我試着看什么CURLOPT_POSTFIELDS
,並CURLOPT_HTTPHEADER
匹配的JS請求,但沒有成功。 但是,我可能在錯誤的位置。
PHP示例
$long_article = "Long article text goes here";
$ch = curl_init("http://api.smmry.com/&SM_API_KEY=XXXXXXXXX&SM_LENGTH=14&SM_WITH_BREAK");
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Expect:")); // Important do not remove
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, "sm_api_input=".$long_article);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 20);
curl_setopt($ch, CURLOPT_TIMEOUT, 20);
$return = json_decode(curl_exec($ch), true);
curl_close($ch);
JavaScript復制
...
const request = require('request-promise');
...
const long_article = 'Long article text goes here';
const r = request({
method: 'POST',
uri: `http://api.smmry.com/&SM_API_KEY=${process.env.SMMRY_API_KEY}`,
// headers: { Authorization: 'array(Expect:)' },
// body: { sm_api_input: long_article },
json: true,
});
request(r)
.then((parsedBody) => { debug(parsedBody); })
.catch((err) => { debug(err); });
我收到的錯誤是{ sm_api_error: 1, sm_api_message: 'INSUFFICIENT VARIABLES' }
所以我至少會找到正確的URL-所以這是一個開始:)
提前致謝!
奧利
您傳遞給uri
嘗試使用查詢字符串,但您沒有正確格式化所請求的URI。 查詢字符串應以?
開頭 並使用&
分隔鍵/值對。 您的查詢字符串以&
而不是?
開頭?
更改:
http://api.smmry.com/&SM_API_KEY=${process.env.SMMRY_API_KEY}&SM_LENGTH=14 &SM_WITH_BREAK
至:
http://api.smmry.com/?SM_API_KEY=${process.env.SMMRY_API_KEY}&SM_LENGTH=14&SM_WITH_BREAK
另外,您要創建一個請求r
,然后將該請求傳遞給request
。 那不是請求承諾模塊的工作方式。 調用request(opts)
,將立即向URI發出請求,並將返回相應的Promise。 請求完成后,將調用所有鏈接的處理程序.then()
.catch()
.finally()
.catch()
.finally()
)。
const request = require('request-promise')
const sm_api_input = 'Long article text goes here'
request({
method: 'POST',
headers: {
'Expect': '100-continue'
},
uri: `http://api.smmry.com/?SM_API_KEY=${process.env.SMMRY_API_KEY}&SM_LENGTH=14&SM_WITH_BREAK`,
form: {sm_api_input},
json: true,
timeout: 20000
})
.then(body => debug)
.catch(err => debug)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.