This question already has answers here:
Ways to circumvent the same-origin policy
(8 answers)
Closed 7 years ago.
I have a RESTful service on a secured site. I can build a request just fine with the REST client in Firefox, but when I try to build it in code I get a 401. Here is my code
(function() {
$.ajax({
url : "https://myrestsite",
type : "GET",
//beforeSend: function (req){
// req.setRequestHeader("Authorization","myauthstring");
// req.setRequestHeader("Content-Type", "application/json");
//},
headers : {
"Authorization" : "myauthstring",
"Content-Type" : "application/json",
},
success : function (){alert('we got here')}
});
})();
This shows up in web developer tools in FF as:
Request-Headers:authorization,content-type
When what I need (from the rest client is FF) is:
Authorization:myAuthstring
Content-Type:application/json
Any clues as to what I am doing wrong?
**edit - turns out I am hitting the cross domain restriction. How does the rest client get around that?
you can pass contentType as an option to $.ajax
$.ajax({
...
contentType: 'application/json'
});
Related
i'm trying to build http adapter with token authorization form ajax request but get 401 error
Status Code:strong text
401 Unauthorized
missing_authorization
$.ajax({
type: "POST",
url: "https://abcd",
data: JSON.stringify({ "template": 1 }),
headers: { "Authorization": "xxxx", "Accept": "application/json",
"Content-Type": "application/json" }
});
function My_adapter() {
path = '/xxx';
var input = {
method : 'post',
path : path,
returnedContentType : 'json',
headers: {'Content-type':'application/json',
'Accept':'application/json', 'Authorization':'Token XXXXX'},
parameters: JSON.stringify({ "template": 1 }),
};
var result=WL.Server.invokeHttp(input);
return result;
}
tnx for your help,
sahar
The error message you see is expected. The client side code you posted shows that you are attempting to invoke MFP server outside of MFP client SDK ( jQuery ajax call). This call does not carry all the required information to the server and server sends the "missing_authorization" message as a result.
If you wish to invoke an adapter, use WLResourceRequest API provided by MFP client SDK. This takes care of handling the authentication handshake with MFP server. More details on the API usage here.
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-2016-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.
For your question, the curl request is sending a header which you have attached as part of the query string in your $.ajax request.
Try the following instead (using beforeSend + xhr) :
// broke this string down so you don't have to scroll
var newurl = "https://mercury.postlight.com/parser?" +
"url=http://www.businessinsider.com/" +
"joel-spolsky-stack-exchange-interview-2016-12";
// set your api key
var apiKey = "<your api key>";
$.ajax({
url: newurl,
dataType: "json",
beforeSend: function(xhr){xhr.setRequestHeader('x-api-key', apiKey);},
success: function(data){
console.log(data.title);
}
})
I'm working with CodeIgniter2 Rest API and AJAX to make requests from a smartphone with PhoneGap to a AWS server with apache.
Everything was working fine when working on my localhost/browser.
But when trying to set up a distant server things got bad.
I have configured my server properly with CORS so that it allows external requests as explained here :
http://dev.nuclearrooster.com/2011/01/03/cors-with-apache-mod_headers-and-htaccess/
To secure the API, I have been setting up an API KEY that I have to pass in the header of my request like so:
$.ajax({
type:"GET",
url: server_url + 'user/available',
headers: { 'X-API-KEY': key },
dataType: 'json'
});
But then, after seeing my ajax called being refused because of an invalid API Key, I have been trying to make sure the server received the key. and it doesnt. when I try to echo my key, its empty.
I can see in my debug console the following:
Request header field X-API-KEY is not allowed by Access-Control-Allow-Headers.
So I have been modifying my .htaccess following this post:
Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Headers "origin, x-requested-with, content-type, x-api-key"
Header add Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"
so now, the message is gone but the problem still remains the same ... why ?
How can I transmit this X-API-KEY through my AJAX call Header so I can authentificate my users ?
Many Thanks
I faced this problem and with weeks of tweaking I was able to get it to work with a hack of a job... I can't remember the exact part that did fix it but will provide with what I am currently using.
Server Side
function __construct(){
parent::__construct();
header("Access-Control-Allow-Origin: " . $_SERVER['HTTP_ORIGIN']);
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
// Access-Control headers are received during OPTIONS requests
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
header("Access-Control-Allow-Headers: X-API-KEY");
}
function available_options(){
$this->response(array('response' => array()), 200);
}
Client Side
function sendData(dataToSend, successCallback) {
window.default_headers['X-API-KEY'] = '_KEY_';
return $.ajax({
type: "POST",
url: server_url + 'user/available',
data: { data : JSON.stringify(dataToSend) }, // serializes the form's elements.
dataType: 'json',
headers: window.default_headers,
xhrFields: {
withCredentials: true
}
});
}
Since you're using a GET request, possibly using JSONP would be of more use, this avoids cross domain requests.
JSONP Request
$.ajax({
type : "GET",
dataType : "jsonp",
url: server_url + "user/available?callback=?", // ?callback=?
success: function(data){
// do stuff with data
}
});
I am making an Ajax request to remote server and sending parameters as POST method.
But I am getting following response:
**"MLHttpRequest cannot load http://rasovai.com/mobilecontact1.php?_dc=1369189135731. Origin null is not allowed by Access-Control-Allow-Origin. "**
I read about this error and found out that it is because of CORS, so I add header to the request as follows:
Ext.Ajax.defaultHeaders = {
'Accept': 'application/json',
'Accept': 'Access-Control-Allow-Origin: *',
'Accept': 'Access-Control-Allow-Credentials: true',
'Accept': 'Access-Control-Allow-Methods: OPTIONS, GET, POST',
'Accept': 'Access-Control-Allow-Headers: Content-Type, Depth, User-Agent, X-File-Size, X-Requested-With, If-Modified-Since, X-File-Name, Cache-Control'
};
but still I am getting the same error in response.
I am able to hit the url on server, but not able to pass the parameters.
Can anyone help me in this regard?
Thanks
Ishan jain
Those headers need to be sent by the server, not the client.
If you are using Chrome browser you can use --disable-web-security flag to allow cross domain requests and if you are building this into app this will work fine. Have a look at this thread for more details : How to use json proxy to access remote services during development
If you want to pass the params to the server then you can do it as following.
Ext.Ajax.request({
url : serverURL,
jsonData : requestParams, // Object which encapsulates the request params
method : 'POST',
withCredentials: true,
useDefaultXhrHeader: false,
// List of header params can be sent as follows
headers : {
"Content-Type" : "application/json",
"Accept" : "application/json",
"Access-Control-Allow-Origin":"http://localhost:8080",
"Authorization":auth
},
username : 'mobiliser',
password : 'secret',
success : function(response) {
}
failure : function ()
{
}
As you said in your question that, the server is on a different domain, you may have to use JSONP request.
Let me know if you have any questions.
Thanks-
Gendaful
I'v been struggling with POST on the Picasa API.
Here's code:
$.ajax({
type: "POST",
url: 'https://picasaweb.google.com/data/feed/api/user/' + uid + '/albumid/' + album_id + '/photoid/' + photo_id,
crossDomain: true,
data: { content: content },
success: function() { alert("Success"); },
error: function() { alert('Failed!'); }
});
I've already retrieved some information via GET without problems.
Now comes the fun part, when I try to test the service with Google this error occurs:
XMLHttpRequest cannot load
https://picasaweb.google.com/data/feed/api/user/userid/albumid/albumid/photoid/photoid?content=foo%bar.
Origin http://localhost:3000 is not allowed by
Access-Control-Allow-Origin
.
And when I try in Firefox the request header method is changed to OPTIONS and status is 204: no content.
Also, I've tried to change datatype to jsonp but then HTTP method changes to GET and it retrieves information about the picture.
Access-Control-Allow-Origin is coming because your are making a ajax call to a server which is not same as your current domain.
Read more here
jsonp will not help for POST request because you can only make GET request with jsonp.
IMHO you should try to make the POST request from server side instead of client side script.