Why is my ajax having a validation error querying yelp api? - ajax

First question here, so please forgive me if I don't ask it correctly.
I have the following code:
function getMapPlaces() {
var key =
"_961jkjpPEKGMX6YlEZm8awCLH1avefv5RUIhm6ciV_8kfRRr-gRay5GIICt9Ih-ggqoKNJdnSD7rBuIwmcbiaHSLUFWeJmOaHmzO5t4UwYvJCfX7hy38gy4IhUWX3Yx;";
var settings = {
async: true,
crossDomain: true,
url:
"https://cors-anywhere.herokuapp.com/https://api.yelp.com/v3/businesses/search",
method: "GET",
headers: {
Authorization: "Bearer " + key,
//"x-rapidapi-host": "YelpAPIserg-osipchukV1.p.rapidapi.com",
//"x-rapidapi-key": "629a103ae7msh8d2e000534865ffp18dc6ejsna10a77d719b1",
//"content-type": "application/x-www-form-urlencoded",
},
data: {
location: "Harrisburg",
accessToken:
"_961jkjpPEKGMX6YlEZm8awCLH1avefv5RUIhm6ciV_8kfRRr-gRay5GIICt9Ih-ggqoKNJdnSD7rBuIwmcbiaHSLUFWeJmOaHmzO5t4UwYvJCfX7hy38gy4IhUWX3Yx",
},
};
$.ajax(settings).done(function (response) {
console.log(response);
});
}
getMapPlaces();
But am getting the following error:
{error: {code: "VALIDATION_ERROR",…}}
error: {code: "VALIDATION_ERROR",…}
code: "VALIDATION_ERROR"
description: "'Bearer ;' does not match '^(?i)Bearer [A-Za-z0-9\-\_]{128}$'"
field: "Authorization"
instance: "Bearer ;"
with my api key replacing . What am I doing wrong here?

Try removing semicolon (;) at the end of your key value (the last character in the string).
The regex ([A-Za-z0-9\-\_]{128}$) error seems self explanatory.

Your authorization header does not match the regular expression they provide for validation. See for yourself:
var key = "_961jkjpPEKGMX6YlEZm8awCLH1avefv5RUIhm6ciV_8kfRRr-gRay5GIICt9Ih-ggqoKNJdnSD7rBuIwmcbiaHSLUFWeJmOaHmzO5t4UwYvJCfX7hy38gy4IhUWX3Yx;";
var authorizationHeader = "Bearer " + key;
var validator = new RegExp('^Bearer [A-Za-z0-9\-\_]{128}$');
authorizationHeader.match(validator);

Related

How do I get Postman to call my Web API

I'm got the pluggin Postman for Chrome. I'm just wondering how I would get Postman to call my web API.
Current, I'm using this AJAX call written in Javascript:
alert("Getting security token");
// Do AJAX call to get security token:
$.ajax({
url: [security token url],
type: "POST",
headers: {
Accept: "application/json"
},
ContentType: "application/x-www-form-urlencoded",
data: {
grant_type: "password",
username: [username],
password: [password]
}
}).done(function(data)
{
var accessToken = data.access_token;
alert(accessToken);
alert("Getting json string.");
// Now that we have access token, send it along with the request for the json string:
$.ajax({
// meta data sent as URL parameters:
url: [url to get json string]
type: "GET",
headers: {
Authorization: "Bearer " + accessToken // access token
},
contentType: false,
processData: false
}).done(function(data)
{
$("#jsonDiv").html(data);
}).fail(function(jqXhr, textStatus, errorThrown)
{
alert("jqXhr = " + JSON.stringify(jqXhr));
alert("textStatus = " + textStatus + ", errorThrown = " + errorThrown);
});
}).fail(function(jqXhr, textStatus, errorThrown)
{
alert("jqXhr = " + JSON.stringify(jqXhr));
alert("textStatus = " + textStatus + ", errorThrown = " + errorThrown);
});
What would I have to do in Postman to accomplish the equivalent of this?
Thanks
There are a few ways to achieve this, but here are some steps to get you started. Create two 2 APIs:
The first to call the "security token url" with the POST method.
Add the header:
Accept: application/json
Then under body, select x-www-form-urlencoded and then add the following keys (and their appropriate values):
grant_type : password
username :
password :
Off the top of my head I think the password grant_type also requires client_id and client_secret, but I don't see that in your code above so maybe you don't need it.
If you hit send you should get an access token back.
In your second API, set the method to GET and supply the appropriate URL. Then in the headers add:
- Authorization : Bearer
If you want to get fancy you can use the test tab to write the access token to an environment variable and then use the result in your second call.
You don't need to get a new access token for each call however so you can just keep using the same token until it expires.
Sorry if you already knew how to do this, I couldn't tell your level of expertise from your question. Hope this helps.

Using ajax in Servant

I use Haskell with servant-0.7.1 fo realisation server.Below is my source code:
type UserRestAPI
= "rest" :> "users" :> Get '[JSON] [User]
:<|> "rest" :> "user" :> ReqBody '[JSON] User :> Post '[PlainText] Text
serverUserRestAPI :: ServerT UserRestAPI AppM
serverUserRestAPI = usersGet :<|> userPost
userPost :: User -> AppM Text
userPost user = do
newUser <- runDb $ do insert user
liftIO $ putStrLn $ show newUser
return $ append (toPathPiece newUser) "\r\n"
The model of User:
let mongoSettings = (mkPersistSettings (ConT ''MongoContext)) {mpsGeneric = False}
in share [mkPersist mongoSettings, mkMigrate "migrateAll"] [persistLowerCase|
User
fam String
im String
ot String
email String
login String
pswd String
deriving Show
|]
$(deriveJSON defaultOptions ''User)
For testin curl was used, as shown below.
curl --verbose --request POST --header "Content-Type: application/json" \
--data '{"userFam": "Fam", "userIm": "Im", "userOt": "Ot", "userEmail": "mail#mail.ru", "userLogin": "test", "userPswd": "test"}' \
http://127.0.0.1:3000/rest/user
Everything is working. The data added to the database.But when I use ajax from backend, as shown below.
var formElement = $("#id_form");
var formData = formElement.serializeArray();
var objectData = {};
for(var i = 0; i < formData.length; i++)
objectData[formData[i].name] = formData[i].value;
$.ajax({
type: "POST",
async: true,
url: "/rest/user",
dataType: "text",
cache : false,
contentType : "application/json",
data: objectData,
success: function(result){
consoloe.log(result)
},
error: function(jqXHR, status, err) {
console.log(err)
}
});
I get an error!
jquery.js:4 POST http://127.0.0.1:3000/rest/user 400 (Bad Request)
The debugger checked object objectData. All right (Object {userFam: "qqq", userIm: "www", userOt: "eee", userEmail: "rrr", userLogin: "ttt"…}).
I can not understand what was going on.
it's really a problem with your ajax call as you don't provide a valid JSON object but just objectData.toString() as data: - the common solution is to use JSON.stringify:
$.ajax({
type: "POST",
async: true,
url: "/rest/user",
dataType: "json",
cache : false,
data: JSON.stringify(objectData),
success: function(result){
// ...
},
error: function(jqXHR, status, err) {
console.log(err)
}
});
another great example what is wrong with untyped languages ;)

How do you format an AJAX request to an API with an authentication key using Mithril?

The following GET request works using jQuery:
$.ajax({
url: "https://yoda.p.mashape.com/yoda?sentence="+phrase,
headers: {"X-Mashape-Key": "superSecretKey", "Accept": "text/plain"},
success: function(data) {
console.log(data);
},
error: function(data) {
console.log(data);
}
})
But the adaptation that follows using Mithril will not work:
Yoda.submit = function (phrase) {
console.log(phrase);
return m.request({
method: 'GET',
url: "https://yoda.p.mashape.com/yoda?sentence=" + phrase,
headers: {"X-Mashape-Key": "superSecretKey",
"Accept": "text/plain"}
});
}
I've tried different variations after consulting the documentation at https://lhorie.github.io/mithril/mithril.request.html and searching for similar examples. I'm considering using 3rd party libraries but thought I'd try here before I go too far down the rabbit hole. The error message that I get when I try to make an AJAX request is that I'm missing the API key even though it's right there.
UPDATE:
I've since learned, in addition to the answer marked below, that Mithril automatically parses API responses as JSON. Since I'm getting back a string response from this API, I have to include in my m.request object the following entry:
deserialize: function(value) {return value;}
Deserialize tells Mithril to return the response value as-is, not as JSON.
You need to use the config attribute:
m.request({method: 'GET', url: "https://yoda.p.mashape.com/yoda?sentence=" + phrase,
config: function(xhr, options) {
xhr.setRequestHeader("X-Mashape-Key", "superSecretKey")
xhr.setRequestHeader("Accept", "text/plain")
}}).then(function(data) {
console.log('success: ', data)
}, function(err) {
console.log('error: ', err)
})

ajax POST a JSON array to nodejs server removes keys

RESOLVED! see solution at bottom of this post...I have been stuck on this problem for about 2 days now and it's starting to get to me. I am trying to POST a Json array to my node server (cross-domain) and insert it to a cloudant db. This question is more about just getting the json over in the correct format. Here is my client side json and ajax:
function stress(){
var start = new Date().getTime();
$.ajax({
type: 'POST',
url: 'url/',
crossDomain: true,
data: JSON.stringify(products),
dataType: 'json',
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
success: function(responseData, textStatus, jqXHR) {
var end = new Date().getTime();
var millis = (end - start);
var duration = (millis/1000);
alert(responseData.msg +'Duration(seconds): ' + duration);
},
error: function (responseData, textStatus, errorThrown) {
alert('POST failed. ' + JSON.stringify(responseData) + " status: " + textStatus + " Error: " + errorThrown);
}
});
}
var products = [
{
name: 'War Room Table',
year: '2005',
color: 'tan',
country: 'USA',
description: 'A Beautiful War Room table. Includes all 4 legs!',
usaDollarPrice: 150
},
{
name: 'Power Strip',
year: '2000',
color: 'white',
country: 'USA',
description: 'A very old power strip, may or may not protect against power surges.',
usaDollarPrice: 16
}];
My Node.js server side:
exports.create = function(req, res) {
var data = req.body;
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Content-Type', 'application/json');
//var parsed = JSON.parse(data);
var msg = {};
for(product in data){
db.insert(data[product], function (err, body, headers) {
if (!err) {
msg.msg = 'success!';
console.log(JSON.stringify(msg);
}
else {
msg.msg = 'Error on insert, maybe the item already exists: ' + err
console.log(JSON.stringify(msg);
}
});
}
}
I have tried a multitude of different things. What I basically want is a object on the server side that I can iterate through and insert to the cloudant database, each as a separate doc. I have tried many combinations of JSON.stringify and JSON.parse. using parse has given no luck as I get an error saying SyntaxError: Unexpected token o which I read that means it is already an object, but I cannot access data in any way ( data[0], data.name, data[0].name, nothing on the server side). I have also tried sending the json from the client side in different ways (in ajax - data: JSON.stringify({prod:products}) and still no luck.
Having the json on the server side (same as products above) inserts the docs in the correct order, the problem is when I sent that same json over a ajax post and to a cross-domain server. I cannot get that json out. Any idea or help would be very appreciated, thanks
Solution:
I ended up putting the object into another array and using that to be sent to the server. Here is the working ajax in the client side, notice the data:{data:products} that's what did it for me. Also below is the products json and also how to access it on the nodejs server side.
$.ajax({
type: 'POST',
url: 'url/',
crossDomain: true,
data: {data:products},
dataType: 'json',
contentType: "application/x-www-form-urlencoded",
success: function(responseData, textStatus, jqXHR) {
var end = new Date().getTime();
var millis = (end - start);
var duration = (millis/1000);
alert(responseData.msg +'Duration(seconds): ' + duration);
},
error: function (responseData, textStatus, errorThrown) {
alert('POST failed. ' + JSON.stringify(responseData) + " status: " + textStatus + " Error: " + errorThrown);
}
});
var products = [
{
name: 'War Room Table',
year: '2005',
color: 'tan',
country: 'USA',
description: 'A Beautiful War Room table. Includes all 4 legs!',
usaDollarPrice: 150
},
{
name: 'Power Strip',
year: '2000',
color: 'white',
country: 'USA',
description: 'A very old power strip, may or may not protect against power surges.',
usaDollarPrice: 16
}];
Here is how to access it on the server side. Keep in mind this is all for cross-domain Post, but should work otherwise.
exports.create = function(req, res) {
var body = req.body;
//body.data[0] will get you the first object in the json, in this case it will be the war room table.
//If you use console.log to see it make sure you JSON.stringify(body.data[0]) or else you wil see [Object] [Object]
Also very important to include this in your server/app.js The extended: true part is important. Example
app.use(bodyParser.urlencoded({ extended: true }));
You are stringifying the json data before sending it to the node server, try only
data:products You will also need the node module body-parser using it you will be able to access POSTed data through ajax, see this answer also
I am new to ajax. Please check if this helps. I think I had a similar problem which is solved now.
Please see the answer posted by me
How to send array of arrays as data in $.ajax()?

ajax POST method is not working

I am trying to send the data via ajax POST method my code is
$.ajax({
url: myUrl + "?token=" + accessToken + "&key=" +dev_key,
dataType: 'jsonp',
type: 'POST',
data: sendXML,
success: function () {
alert("z");
}
});
But the type: 'POST' is not working I am getting the following error on console:
Status Code:405 HTTP method GET is not supported by this URL
Have you tried using $.post ?
Example:
$.post(
myUrl,
{
token: accessToken,
key: dev_key
},
function(result){
alert(z)
}
)
P.S. Isn't ? missing after myUrl?
i think you forgot the ? in the token key like this
mySql + "?token="
otherwise, try this:
jQuery.post(
myUrl + "?token=" + accessToken + "&key=" +dev_key,
sendXML,
function() {
alert('z');
},
'JSONP'
);

Resources