javascript: how to make AJAX call based on the avaiable cURL request — Stack Overflow

Converting curl cmd to jquery $.ajax()

I’m trying to make a api call with jquery ajax, I have curl working for the api, but my ajax is throwing HTTP 500

I have a curl command working that looks like this:

curl -u "username:password" -H "Content-Type: application/json" -H "Accept: application/json" -d '{"foo":"bar"}' http://www.example.com/api

I tried ajax like this, but it is not working:

$.ajax({ url: "http://www.example.com/api", beforeSend: function(xhr) { xhr.setRequestHeader("Authorization", "Basic " btoa("username:password")); }, type: 'POST', dataType: 'json', contentType: 'application/json', data: {foo:"bar"}, success: function (data) { alert(JSON.stringify(data)); }, error: function(){ alert("Cannot get data"); }
});

What am I missing ?

Javascript: how to make ajax call based on the avaiable curl request

Currently in my web app project, I need to parse the content of a web page, and after some searching, I found that Mercury Web Parser API is quite suitable for me.
And I have some experience with such kind of third party APIs, generally speaking I can get my desired result.
But for this API, I can’t find documentation about the API usage on the official website.
Based on the my study, it provide two methods:
first is cURL as following:
curl -H "x-api-key: myapikey" "https://mercury.postlight.com/parser?url=https://trackchanges.postlight.com/building-awesome-cms-f034344d8ed"

the myapikey is the API key I get from the website. Then I can get the result in JSON format, which is the main content of the web page specified by the url parameter. It works well for me, I mean the cURL method.

And on the website, it said that the second method is HTTP call, which is just what I need:

GET https://mercury.postlight.com/parser?url=https://trackchanges.postlight.com/building-awesome-cms-f034344d8ed
Content-Type: application/json
x-api-key: myapikey

So based on my understanding, I use jquery AJAX method to do this as following:

 var newurl = "https://mercury.postlight.com/parser?url=http://www.businessinsider.com/joel-spolsky-stack-exchange-interview-2022-12&x-api-key=myapikey" $.ajax({ url: newurl, dataType: "jsonp", success: function(data){ console.log(data.title); } })

here I made JSONP request because of the Cross origin issue.
But now I face 401 error message (401 Unauthorized. The request has not been applied because it lacks valid authentication credentials for the target resource)

For now my guess is that the apikey is not correctly passed to server. So based on the cURL’s successful call, can I get the correct format for AJAX call?

Update:
Based on the following answers ,I tried to set the request header as following:

 $.ajax({ url: newurl, dataType: "jsonp", beforeSend: function(xhr){ console.log(apiKey); xhr.setRequestHeader('x-api-key', apiKey); }, /* headers: { "x-api-key": "M1USTPmJMiRjtbjFNkNap9Z8M5XBb1aEQVXoxS5I", "contentType": 'application/json' }, */ success: function(data){ console.log("debugging") console.log(data.title); }, error: function (error) { console.log(error) } })

I tried both beforeSend and headers. But still can’t work and get the following trackback error message:

 send @ jquery.js:8698 ajax @ jquery.js:8166 addNewArticle @ topcontroller.js:18 fn @ VM783:4 e @ angular.js:281 $eval @ angular.js:147 $apply @ angular.js:147 (anonymous) @ angular.js:281 dispatch @ jquery.js:4435 elemData.handle @ jquery.js:4121

And for the last send function, still 401 error.

But the ajax error handling part shows that the readyState:4 and status: 404 result. So what’s going here.

Эмулировать ajax запрос при помощи curl запроса

У меня есть серверное апи, в котором используются сессии, ориентировочно он выглядит так:

if(!session_id()) @session_start();
$_SESSION['test']=$_POST['value'];

Если обращаться к нему с клиента XHR запросом, jquery ajax’ом в частности, то всё впорядке, данные сохраняются в суперглобальном массиве $_SESSION и я могу их использовать при последующих ajax запросах от того же пользователя:

$.post('api.php',{value:123})

Однако если я вызываю апи из другого php скрипта curl запросом, то сессия не закрепляется за пользователем, а живёт своей отдельной жизнью:

 $ch=curl_init(); curl_setopt($ch,CURLOPT_URL,'localhost/api.php'); curl_setopt($ch,CURLOPT_RETURNTRANSFER,true); curl_setopt($ch,CURLOPT_POST,true); curl_setopt($ch,CURLOPT_POSTFIELDS,"value=123"); curl_setopt($ch,CURLOPT_TIMEOUT,1); $res=curl_exec($ch);

Вопрос в том, как сделать curl запрос максимально похожем на ajax запрос, чтобы, по крайней мере, php сессия закреплялась за пользователем, который этот curl активировал? Если я правильно понимаю, то нехватает каких-то заголовков, но я плохо разбираюсь в устройстве обоих технологий, потому прошу помощи.

Send ajax request through curl

An API request needs to be sent. For some reason, the server is blocking CURL request, but it approves an XHR ajax request. I could send an ajax request, but another problem arises — Mixed content my website is served over HTTPS but the request that needs to be sent is over HTTP so I cannot use ajax.

I am looking for a way to simulate ajax request through CURL, in some way, trick the server to believe that the CURL request is indeed an ajax request.

Here’s what I have tried.

This is my CURL request.

 $ch = curl_init(); curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (X11; Linux x86_64)'); curl_setopt($ch, CURLOPT_REFERER, 'server's url'); curl_setopt($ch, CURLOPT_AUTOREFERER, true); curl_setopt($ch, CURLOPT_HTTPHEADER, array( 'Accept:application/json, text/javascript, */*; q=0.01', 'Accept-Encoding:gzip, deflate', 'Accept-Language:en-US,en;q=0.9', 'Connection:keep-alive', 'Content-Type: application/json; charset=utf-8', 'X-Requested-With: XMLHttpRequest', '__RequestVerificationToken: $token' )); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); curl_setopt($ch, CURLOPT_MAXREDIRS, 10); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); curl_setopt($ch, CURLOPT_COOKIEJAR, base_path().'/cookies.txt'); curl_setopt($ch, CURLOPT_COOKIEFILE, base_path().'/cookies.txt'); $buffer = curl_exec($ch); if(curl_error($ch)) { $buffer = curl_error($ch); } curl_close($ch);
return $buffer;

This curl request is blocked

But, this ajax request goes through my localhost, but since my live website uses HTTPS I cannot really use it.

 $.ajax({ type: "get", xhrFields: { withCredentials:true }, url: http://apiendpoint.com, success: function(data) { // console.log(data); } })
Похожее:  Дети TaVie - Благотворительный фонд