jquery 在JavaScript中执行curl请求?

c86crjj0  于 2024-01-07  发布在  jQuery
关注(0)|答案(5)|浏览(154)

可以用jQuery或JavaScript发送curl请求吗?
就像这样:

  1. curl \
  2. -H 'Authorization: Bearer 6Q************' \
  3. 'https://api.wit.ai/message?v=20140826&q='

字符串
所以,在PHP中提交一个表单,像这样:

  1. $header = array('Authorization: Bearer 6Q************');
  2. $ch = curl_init("https://api.wit.ai/message?q=".urlEncode($_GET['input']));
  3. curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
  4. curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
  5. $response = curl_exec($ch);
  6. curl_close($ch);


我正在尝试执行这个curl请求,它返回json,然后我计划用jQuery的$.get()函数解析它。

mf98qq94

mf98qq941#

curl是一个command in linux(和一个library in php)。Curl通常会发出一个HTTP请求。
你真正想做的是从JavaScript发出一个HTTP(或XHR)请求。
对于初学者来说,使用这个词汇表你会发现一堆例子:Sending authorization headers with jquery and ajax
本质上,你会想调用$.ajax,并为头部等提供一些选项。

  1. $.ajax({
  2. url: 'https://api.wit.ai/message?v=20140826&q=',
  3. beforeSend: function(xhr) {
  4. xhr.setRequestHeader("Authorization", "Bearer 6QXNMEMFHNY4FJ5ELNFMP5KRW52WFXN5")
  5. }, success: function(data){
  6. alert(data);
  7. //process the JSON data etc
  8. }
  9. })

字符串

wpx232ag

wpx232ag2#

您可以使用JavaScriptFetch API(在浏览器中可用)发出网络请求。
如果使用node,则需要安装node-fetch包。

  1. const url = "https://api.wit.ai/message?v=20140826&q=";
  2. const options = {
  3. headers: {
  4. Authorization: "Bearer 6Q************"
  5. }
  6. };
  7. fetch(url, options)
  8. .then( res => res.json() )
  9. .then( data => console.log(data) );

字符串

nwsw7zdq

nwsw7zdq3#

是的,使用getJSONP。这是进行跨域/服务器Java调用的唯一方法。(* 或者在不久的将来)。类似于

  1. $.getJSON('your-api-url/validate.php?'+$(this).serialize+'callback=?', function(data){
  2. if(data)console.log(data);
  3. });

字符串
回调参数将由浏览器自动填充,所以不用担心。
在服务器端('validate.php'),您将看到类似于以下内容的内容

  1. <?php
  2. if(isset($_GET))
  3. {
  4. //if condition is met
  5. echo $_GET['callback'] . '(' . "{'message' : 'success', 'userID':'69', 'serial' : 'XYZ99UAUGDVD&orwhatever'}". ')';
  6. }
  7. else echo json_encode(array('error'=>'failed'));
  8. ?>

展开查看全部
yh2wf1be

yh2wf1be4#

既然你可以在两个不同的地方使用JavaScript:客户端和服务器,我将尝试分享两者。

客户端首先使用:

JavaScript有原生的Ajax支持,带有XMLHTTPRequest(但更难使用)

  1. var xhr = new XMLHttpRequest();
  2. xhr.open("GET", "http://example.com/api/data", true);
  3. xhr.onreadystatechange = function() {
  4. if (xhr.readyState === 4 && xhr.status === 200) {
  5. console.log(xhr.responseText);
  6. }
  7. };
  8. xhr.send();

字符串
我会使用Fetch API,因为它更友好:

  1. fetch('http://example.com/api/data')
  2. .then(response => {
  3. if (!response.ok) {
  4. throw new Error('Network response was not ok');
  5. }
  6. return response.json();
  7. })
  8. .then(data => console.log(data))
  9. .catch(error => console.error('Fetch error:', error));

现在服务器:

在JavaScript/NodeJs中运行cURL有几个选项,
1.使用exec命令,执行命令,包括cURL
1.使用node-libcurl,作为libcurl API的绑定
1.使用具有相同目标的替代方案!由于cURL的目标是请求HTTP,因此我们在这里有几个选项,包括:

  • 请求
  • 内置HTTPS
  • 修得
  • 等等.

我在这里写了更多关于这个:How to use cuRL in Javascript and it's alternative.,请随意阅读。

exec comamnd示例

  1. const { exec } = require('child_process');
  2. exec('curl -s https://example.com', (error, stdout, stderr) => {
  3. if (error) {
  4. console.error(`Error: ${error}`);
  5. return;
  6. }
  7. if (stderr) {
  8. console.error(`stderr: ${stderr}`);
  9. return;
  10. }
  11. console.log(`stdout: ${stdout}`);
  12. });

node-libcurl示例

  1. const { curly } = require('node-libcurl');
  2. async function run() {
  3. const { statusCode, data, headers } = await curly.get('https://www.google.com')
  4. console.log(statusCode)
  5. console.log('---')
  6. console.log(data)
  7. }
  8. run();

Axios示例(作为替代)

  1. const axios = require('axios');
  2. const fs = require('fs');
  3. Axios.get('https://example.com')
  4. .then(response => {
  5. fs.writeFile('index.html', response.data, (err) => {
  6. if (err) {
  7. console.error('Error writing file:', err);
  8. } else {
  9. console.log('File saved as index.html');
  10. }
  11. });
  12. })
  13. .catch(error => {
  14. console.error('Error fetching URL
  15. :', error);
  16. });


我希望它能帮上忙!

展开查看全部
hsgswve4

hsgswve45#

目前接受的答案是进行远程呼叫,您可能必须处理跨站点问题。
但是如果您只是想在服务器端运行Linux curl,就像使用PHP一样,那么可以使用这个。
下面是我使用nodejs执行curl请求的函数。
这是一个简单的blog函数,不需要node之外的特殊包。你可以对结果数据和错误做你想做的事情,或者返回它在另一个blog函数中使用。
我只是举个例子。

  1. const util = require('util');
  2. const exec = util.promisify(require('child_process').exec);
  3. const goCurl = async (url) => {
  4. const { stdout, stderr } = await exec(`curl '${url}'`);
  5. console.log('data:', stdout);
  6. console.error('err:', stderr);
  7. }
  8. const url = `https://static.canva.com/web/a7a51d4eae8626ead168.ltr.css`;
  9. goCurl(url);

字符串

展开查看全部

相关问题