get the information from Naver LINE API through http request - ajax

I have a question on the chat app, Naver LINE. There is an API that provides login authentication called LINE login.
I've follow the instructions on the documents and run the querystring and I got a callback URL that gives me the code look like this,
https://sample.com/callback?code=b5fd32eacc791df&state=123abc
Now, the document says I need to use the code in a http request using post method. I got the following,
XMLHttpRequest cannot load https://api.line.me/v1/oauth/accessToken/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://xxxxxxxxxxxxxxxxxxxxxxxxxxx' is therefore not allowed access. The response had HTTP status code 404.
Below is the request I wrote,
$.ajax({
url: "https://api.line.me/v1/oauth/accessToken/",
type: "POST",
xhrFields: {
withCredentials: true
},
crossDomain: true,
data: JSON.stringify(data),
dataType: "json",
success: function (response) {
var resp = JSON.parse(response)
alert(resp.status);
},
error: function (xhr, status, state, error) {
alert("error", xhr, status);
console.log(xhr);
console.log(status);
console.log(state);
console.log(error);
}
});
data is the credentials I put in so LINE would pass me the user's information.
Is there anything I did wrong? If so, how can I fix this?
Thanks ahead.

Related

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-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);
}
})

Ivalid response for preflight (401) when trying to get json from webservice

I spent my last 5 working hours searching for this problem, but none of the solutions have helped me, so here goes:
I have an asmx webservice returning JSON
<System.Web.Services.WebMethod()> _
<Script.Services.ScriptMethod(ResponseFormat:=Script.Services.ResponseFormat.Json)> _
Public Function GetObjectsByObjectType(ByVal ObjectType As String)
Dim db As New Database(System.Web.Configuration.WebConfigurationManager.AppSettings("strConnectionStr"))
Return GetJson(DirectCast(db.ExecuteSelect("##queryHere##"), DataSet).Tables(0))
End Function
Public Function GetJson(ByVal dt As DataTable) As String
Return New JavaScriptSerializer().Serialize(From dr As DataRow In dt.Rows Select dt.Columns.Cast(Of DataColumn)().ToDictionary(Function(col) col.ColumnName, Function(col) dr(col)))
End Function
This is hosted on a server (and works fine if I use it directly on the server) and I'm trying to access it from my localhost test-server like this
$.ajax({
type: "POST",
url: "http://linkToServer/DatabaseService.asmx/GetObjectsByObjectType",
data: JSON.stringify({ stuff }),
dataType: "json",
timeout: 3000,
contentType: "application/json;charset=utf-8",
xhrFields: {
withCredentials: true
},
success: function (msg) {
console.log(msg);
},
error: function (xhr, ajaxOptions, errorthrown) {
console.log(errorthrown);
}
});
But i always end up getting either an instant timeout response or
XMLHttpRequest cannot load [...]. Response for preflight has invalid HTTP status code 401
I already tried the following:
setting crossDomain: true
supplying credentials with username: .., password: ..
setting the following server-side:
Access-Control-Allow-Origin "*"
Access-Control-Allow-Credentials "true"
Access-Control-Allow-Headers "Content-Type"
Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS"
(not sure about the formatting, but they are set correctly, I just didnt want to copy the web.config xml stuff)
and lots of other small changes, setting-wise
The only working solution I found was this:
If I remove the
contentType: "application/json;charset=utf-8"
from the ajax request, I get my JSON result wrapped in a XML document, which I could parse, but I would rather have the JSON directly.
So do you have any idea how I can set thing up, so I can get the JSON result?

JS Cross-Domain request with JSONP

I'm trying to perform a cross domain call. so i'm using JSONP.
The problem is that the response is not json, but an html.
The request works fine and i see the response with status 200 in the network console, however the error function is the one being called, as the expected response is JSON whereas I get an html.
Do you have alternatives for using JSONP for cross domain request?
If i'm using JSONP but the request is not, can I somehow expect a value which is not a json? (tried dataType: 'jsonp text' and didn't work)
Although I get an error with the ajax call, is there a way to extract the result of the request, as it still returns status 200, it's just not accessible ?
$.ajax
({
type: "GET",
url: myurl,
crossDomain:true,
dataType: 'jsonp',
contentType: "text/html; charset=utf-8",
success: function (data) {
console.log(data);
},
error: function (data) {
console.log(data);
},
});

How to show AJAX response message in alert?

I am sending username and password as request parameter to the server in AJAX and trying to show the response message. But not able to showing the response message.In fiddler it is showing the response message. But while on the browser screen it is not showing.PLEASE somebody help me out where i am wrong or need to change anything..
I have written like this-
$(document).ready(function () {
$("#btnCity").click(function () {
$.ajax({
type: "POST",
url: "http://test.xyz.com/login",
crossDomain: true,
contentType: "application/json; charset=utf-8",
data: { username: "abc", password: "1234" },
dataType: "JSONP",
jsonpCallback: 'jsonCallback',
async: false,
success: function (resdata) {
alert(resdata);
},
error: function (result, status, err) {
alert(result.responseText);
alert(status.responseText);
alert(err.Message);
}
});
});
});
TL;DR: I guess the problem is on the server side of your code (that we don't know yet).
At first: I don't know why it fails for you. I've taken your code and ran it against a public available JSONP API, that returns the current IP of your system and it worked.
Please try yourself using the URL: http://ip.jsontest.com/.
So most probably, the server doesn't return the right response to the JSONP request. Have a look at the network tab in developer tools. With your current code, the answer of the server should be something like:
jsonCallback({'someResponseKeys': 'someResponseValue'});
Note: The header should contain Content-Type:application/javascript!
BTW, even if this doesn't for now solve your problem - here are some tweaks, I'd like to advice to you:
Don't set async to false, at the documentation of jQuery.ajax() says:
Cross-domain requests and dataType: "jsonp" requests do not support synchronous
operation.
You don't need to set a jsonpCallback, because jQuery will generate and handle (using the success function a random one for you. Quote from the docs:
This value will be used instead of the random name automatically generated by jQuery. It is preferable to let jQuery generate a unique name as it'll make it easier to manage the requests and provide callbacks and error handling.
So here comes my code:
$(document).ready(function () {
$("#btnCity").click(function () {
$.ajax({
type: "POST",
url: "http://ip.jsontest.com/",
crossDomain: true,
data: { username: "abc", password: "1234" },
dataType: "JSONP",
success: function (resdata) {
console.log("success", resdata);
},
error: function (result, status, err) {
console.log("error", result.responseText);
console.log("error", status.responseText);
console.log("error", err.Message);
}
});
});
});
A working example can be found here.
Another solution, like Yonatan Ayalon suggested, can be done with a predefined function and then setting the jsonpCallback explicitly to the function that should be called.
if you see the response in Fiddler, it seems that the issue is in the callback function.
you are doing a jsonP call - which means that you need a callback function to "read" the response data.
Do you have a local function that calls "jsonCallback"?
this is a simple jsonP request, which initiates the function "gotBack()" with the response data:
function gotBack(data) {
console.log(data);
}
$.ajax({
url: 'http://test.xyz.com/login' + '?callback=?',
type: "POST",
data: formData,
dataType: "jsonp",
jsonpCallback: "gotBack"
});
You can try with the following methods and close every instance of chrome browser in task manager, then open browser in web security disable mode by the command "chrome.exe --disable-web-security"
success: function (resdata) {
alert(resdata);
alert(JSON.stringify(resdata));
},
And the better option to debug the code using "debugger;"
success: function (resdata) {
debugger;
alert(resdata);
alert(JSON.stringify(resdata));
},

cross domain request issue origin not allow

cross domain request issue
my ajax call code actually when i am running given url directly in browser it shows me json data but using ajax call it always shows me ajax error believe me i tried n follow many things no fruitful result from 18 days.
$.ajax({
crossDomain:true,
type: "GET",
url: 'http://taxihub.azurewebsites.net/Mobile/api/json.php?method=getCompanyList',
contentType: "application/json; charset=utf-8",
dataType: "json",
processData: false,
success: function (data) {
console.log(data);
return;
},
error: function (err) {
console.log("AJAX ERROR");
console.log(err.responseText);
}
});
you can also check this link directly u will see json data coming but i found error i dont know why
"http://taxihub.azurewebsites.net/Mobile/api/json.php?method=getCompanyList"
error: OPTIONS http://taxihub.azurewebsites.net/Mobile/api/json.php?method=getCompanyList Origin lhost:809 is not allowed by Access-Control-Allow-Origin.
please help me i am stuck here from 18 days on this issue
Remove the cross-domain and content-type part and it'll work but you'll have to do a little extra string manipulation work to put it in JSON object:
$.ajax({
type: "GET",
url: 'http://taxihub.azurewebsites.net/Mobile/api/json.php?method=getCompanyList',
dataType: "json",
success: function (data) {
console.log(data.result.getCompanyList[0].CompanyID);
return;
},
error: function (err) {
console.log("AJAX ERROR");
console.log(err);
}
});
}
Actually it seems cross-domain doesn't have any effect with or without it. I guess the server you're targeting doesn't have strict cross-domain prevention but doesn't like the JSON content-type. I'd be glad to get a more specific explanation.
EDIT I used JQuery 1.10.2 if it matters

Resources