Get request of my ajax call getting 411 length required error.
My request is working fine when token is passed via rest-client of Firefox browser
Many thanks for your help....
$.ajax(
'https://example.site.net/users/me/recent',
{
type: 'GET',
beforeSend: function (xhr) {
xhr.setRequestHeader("Content-Type","application/json");
xhr.setRequestHeader("Accept","text/json");
xhr.setRequestHeader("Authorization","Bearer token");
xhr.setRequestHeader("Access-Control-Allow-Headers", "*");
console.log('Fired prior to the request');
},
complete: function (resp) {
console.log(resp);
}
});
Related
I am trying to make a HTTP Post request using angular 6's HttpClientModule.
The POST request I am making is as follows:
const httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/x-www-form-urlencoded' })
};
httpOptions.headers = httpOptions.headers.append('Authorization', 'BasicAuth_Token');
this._http.post(url, {
s: '29'
},httpOptions).subscribe(
data => console.log('Success!',data),
error => console.error('Error!', error)
)
The Post request is successful and I am getting a response.
However I am not getting the response expected.
i.e
When I make the same POST request through AJAX:
$.ajax({
url: url,
type: 'POST',
contentType: "application/x-www-form-urlencoded",
data: { s:'29'},
success: function (data) {
console.log("code - 1000", data);
}
else {
console.log("code - 1001" , data);
}
},
error: function (response) {
console.log("Something went wrong", response);
}
});
I am getting a code - 1000 returned for the same POST data.
However I am getting a code - 1001 for POST in angular 6.
Basically, for the same POST request - though the post is successful
in both ajax and Angular 6 , I am getting different responses for the
same data.
If the post was unsuccesful , I could understand. However I am not
understanding how i am getting two different responses for the same
data i.e being sent to the API.
I am trying to make a post call through ajax from my front end to my express server, but I am getting the error net::ERR_UNKNOWN_URL_SCHEME. The code for ajax is below
function sendSteps(encodedLatLangs) {
$.ajax({
url: 'localhost:3000/route',
type: "POST",
dataType: "jsonp",
contentType: "jsonp; charset=utf-8",
crossDomain:true,
data: JSON.stringify({
steps: encodedLatLangs
}),
success: function (response) {
console.log(done);
},
error: function (request,error) {
console.log('Ajax call gave an error');
}
})};
My console is showing this.
This is how I am handling post request to this endpoint on backend
router.post('/route',function (req, res) {
console.log("Hello Received the Data");
res.send("Hello Received the Data");
//Doing something with the received data
});
Can some throw any light on this.
Thanks.
With JSONP you can sending only GET request (JSONP insert script tags into the DOM).
Your data should be a &key=value string and contentType is application/javascript
Try it:
function sendSteps(encodedLatLangs) {
$.ajax({
url: 'localhost:3000/route',
dataType: "jsonp",
contentType: "application/javascript; charset=utf-8",
crossDomain: true,
data: 'steps=' + encodeURIComponent(JSON.stringify(encodedLatLangs)),
success: function (response) {
console.log(done);
},
error: function (request, error) {
console.log('Ajax call gave an error');
}
});
};
Or use JSON (if you are a server owner and can set up CORS).
It can be done by setting "Access-Control-Allow-Origin" in response header.
Something like this. For more details visit https://enable-cors.org/server_expressjs.html
And also we have to remove "data type" and "content type" from the ajax request.
router.route('/route')
.post((req, res, next) => {
controllers
.post(req.body)
.then(data => {
res.setHeader('Access-Control-Allow-Origin', req.headers.origin);
res.send(message.generateMessage(200, '', data))
})
.catch(err => next(err))
})
I try to make an http request to a freebox ( I don't know if it's exist outside france )
The freebox don't access the CORS request, but she make what I will.
For example if I make a request for power :
http://hd1.freebox.fr/pub/remote_control?code=5818260&key=power&long=false&repeat=1
The freebox player start, and I have a CORS error:
XMLHttpRequest cannot load http://hd1.freebox.fr/pub/remote_control?code=5818260&key=power&long=false&repeat=1. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
It's okay, but I will check the http header for this request, for example if I will check if my code is good, the freebox return 403 for bad code.
I tried to get the statusCode with Jquery :
xhr = $.ajax({
method: "GET",
url: url,
crossDomain: true,
statusCode: {
500: function () {
alert("Une erreur s'est produite !");
},
403: function(){
alert("aaaaa")
throw new badTelecommandeCode();
},
404: function(){
throw new freeboxNotFound();
},
0: function(){console.log(0)}
},
error: function (err) {
console.log(err);
}
});
All this time, the status code is 0, and "error" don't launch. I have this error in console :
XMLHttpRequest cannot load http://hd1.freebox.fr/pub/remote_control?code=5818260&key=power&long=false&repeat=1. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. The response had HTTP status code 403.
You can see the end of this answer
"The response had HTTP status code 403.".
Just before jquery write an error ( in red ):
GET http://hd1.freebox.fr/pub/remote_control?code=5818260&key=power&long=false&repeat=1
I try to catch the error :
try{
xhr = $.ajax({
method: "GET",
url: url,
crossDomain: true,
statusCode: {
500: function () {
alert("Une erreur s'est produite !");
},
403: function(){
alert("aaaaa")
throw new badTelecommandeCode();
},
404: function(){
throw new freeboxNotFound();
}
},
error: function (err) {
console.log(err);
}
});
}
catch(err){
console.log(err);
}
I have try to search, where the error has catch by jquery :
http://code.jquery.com/jquery-2.1.4.js line 8634
Do You find a way for catch the CORS message, and parse it, or catch the jquery message, and why not get the statusCode or any information .
For the little troller, the way "Send a request to freebox developer for accept CORS" is already make, but no answer. I can't pass by a webserver .
My Current challenge is : "I'm a lambda user will see my TV, but my Free Tv Remote don't work, what I can make easily, with my smartphone/PC"
UPDATE1 :
I have make an example :
if it's work good :
xhr = $.ajax({
method: "GET",
url: "http://hd1.freebox.fr/pub/remote_control?code=5818261&key=right&long=false&repeat=1",
crossDomain: true,
statusCode: {
500: function () {
alert("Une erreur s'est produite !");
},
403: function(){
alert("badTelecommandeCode")
},
404: function(){
alert("freeboxNotFound")
}
},
error: function (err) {
// console.log(err);
},
fail:function(jqxhr, textStatus, errorThrown) {
// console.log(errorThrown);
}
});
Good key, good code, my TV make the action, and return a CORS error
I will catch, if the code is bad, or if the key doesn't exist :
xhr = $.ajax({
method: "GET",
url: "http://hd1.freebox.fr/pub/remote_control?code=5818261&key=ping",
crossDomain: true,
statusCode: {
500: function () {
alert("Une erreur s'est produite !");
},
403: function(){
alert("badTelecommandeCode")
},
404: function(){
alert("freeboxNotFound")
}
},
error: function (err) {
// console.log(err);
},
fail:function(jqxhr, textStatus, errorThrown) {
// console.log(errorThrown);
}
});
xhr = $.ajax({
method: "GET",
url: "http://hd1.freebox.fr/pub/remote_control?code=222222&key=ping",
crossDomain: true,
statusCode: {
500: function () {
alert("Une erreur s'est produite !");
},
403: function(){
alert("badTelecommandeCode")
},
404: function(){
alert("freeboxNotFound")
}
},
error: function (err) {
// console.log(err);
},
fail:function(jqxhr, textStatus, errorThrown) {
// console.log(errorThrown);
}
});
I have a CORS, no problem, but how I can catch the text, say the http status .
For information :
freebox.fr is a NAT rules, redirect to my router ( the freebox ), hdX.freebox.fr go to the API for TV player hd number X
Still not certain interpret Question correctly. There does not appear to be a response returned from url . 0 does not appear to be a valid HTTP response code see HTTP status code 0 - what does this mean for fetch, or XMLHttpRequest? . The error logged to console
GET http://hd1.freebox.fr/pub/remote_control?code=5818260&key=power&long=false&repeat=1 net::ERR_CONNECTION_TIMED_OUT
after request below
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://hd1.freebox.fr/pub/remote_control?code=5818260&key=power&long=false&repeat=1", true);
xhr.onload = function() {
console.log(this.status)
}
xhr.onerror = function(e) {
console.log(e, this.status)
}
xhr.send();
I am using the following code to get file-size of a url, the debugger shows requests to be executed with HTTP STATUS CODE 200 returning all headers including 'Content-Length' however my code outputting NULL values for headers (even after the request succeeded).
function checkURL(url) {
try {
var xhr = $.ajax({
type: "HEAD",
url: url,
async: false,
success: function (data) {
result = data;
}
});
console.log('Size :' + xhr.getResponseHeader('Content-Length'));
} catch (e) {
console.log('XHR Error :' + e);
}
}
EDIT # 1
I tested the below code and it works, however not all headers are being displayed. Once again HTTP DEBUGGER shows the elusive 'Content-Length' header to be present in reply to this XHR.
function checkURL(url) {
try {
var xhr = $.ajax({
type : "HEAD",
url : url,
complete : function (XMLHttpRequest, textStatus) {
console.log(XMLHttpRequest.getAllResponseHeaders());
}
});
} catch (e) {
console.log('Check Size XHR Error :' + e);
}
}
Whats is your type HEAD ?
it must be a xml or json !
I have JSON data sending to server. When I submit the for it is printing the data in console but not sending to the server.
It gives the following error
POST http://localhost:8080/rest/review/createReview 400 (Bad Request)
Here is my code
var promise = jQuery.ajax({
url: 'http://localhost:8080/rest/review/createReview',
type: 'POST',
data: '{myReview: myReview}',
dataType: "text",
contentType: "application/json",
success: function (data) {
console.log("Request successful", data);
},
error: function (data) {
console.log("Request failed", data);
}
});
It may be that your data is not valid JSON. Try:
data: JSON.stringify({myReview: myReview})