I used this function
jQuery.ajax({
type: 'POST',
url: urlSubmit,
timeout: 5000,
dataType: 'text',
data: {
date : dataDate,
url : dataUrl,
domaine : dataDomaine,
email : dataEmail,
destinataire : dataDestinataire,
msg : dataMsg
},
"success": function (jqXHR, textStatus, errorThrown) {
console.log("AJAX success :) - statut " + textStatus);
$timeout(successMailZR_alerte, 3000);
},
"error": function (jqXHR, textStatus, errorThrown) {
console.log("AJAX fail :/ - statut " + textStatus);
$timeout(errorMailZR_alerte, 3000);
}
});
Whats the code is doing : code POST to a php script who send an email.
but, since i rewrited my code in a complete angularjs app, i do it like this :
$http({
method: 'POST',
url: urlSubmit,
timeout: 5000,
cache: false,
data: {
date : dataDate,
url : dataUrl,
domaine : dataDomaine,
email : dataEmail,
destinataire : dataDestinataire,
msg : dataMsg
},
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
responseType: 'text',
}).
success(function(data, status, headers, config) {
console.log("AJAX success :) - statut " + status);
$timeout(successMailZR_alerte, 3000);
}).
error(function(data, status, headers, config) {
console.log("AJAX fail :/ - statut " + status);
$timeout(errorMailZR_alerte, 3000);
});
Problem is : with $http, i have a success 200 but nothing is posted and i have no return in my email. What's the problem ?
The problem is that jQuery's POST does send your data as form data (e.g. key-value pairs) (https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Forms/Sending_and_retrieving_form_data) whereas AngularJS sends your data in the request payload. For a difference between the two see the following SO question: What's the difference between "Request Payload" vs "Form Data" as seen in Chrome dev tools Network tab
In order to make your angular script works with your server you have to convert your data to a URL encoded string as described here: How can I post data as form data instead of a request payload?. Simply setting headers: {'Content-Type': 'application/x-www-form-urlencoded'} is not enough.
A different approach would be to adapt the back-end of your application to parse the message payload instead of the form data parameters.
To understand this one need to understand the request headers set by angular and jquery, There are differences with the headers like when request is post by jQuery then header might look like this:
POST /some-path HTTP/1.1
Content-Type: application/x-www-form-urlencoded // default header set by jQuery
foo=bar&name=John
You can see this in form data in the request made in the browser, if you use chrome then you can see this in chrome inspector at network tab, if you click the request then you can see the form data and content headers set by the jQuery.
On the other side with angular js $http service, when a request is made then you can find these:
POST /some-path HTTP/1.1
Content-Type: application/json // default header set by angular
{ "foo" : "bar", "name" : "John" }
The real difference is this you have a request payload not usual form data which is used by jQuery. so you need to do something extra at the server side like below.
Use this:
$data = json_decode(file_get_contents("php://input"));
echo $data->date;
// and all other params you have sent
This is due to its default headers
Accept: application/json, text/plain, * / *
Content-Type: application/json
and jQuery unlikely have something else:
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Related
I am developing a simple REST service in flask.
I have been trying to implement basic authorization.
Whilst, I can pass the username and password from the webpage using manual entry, I can't seem to read them from the header.
Here is my code:
On the server
def test():
if request.authorization and request.authorization.username == '***' and request.authorization.password == '***':
return "Authorized"
else:
return make_response('Authorization failed', 401, {'WWW-Authenticate': 'Basic realm ="Login Required"'})
On the client - using JavaScript
<script>
$(document).ready(function(){
$("#authButton").click(function(){
$.ajax({
xhrFields: {
withCredentials: true
},
headers: {
'Authorization': "Basic " + btoa("***:***")
},
url: "********:5001/",
type: 'GET',
success: function(){
console.log("success");
},
error: function (){
console.log("error");
},
});
});
});
</script
>
I have also tried the Javascript code without the xhr fields section, but for neither do I get anything returned at all.
If I don't send the headers from the client it works and simply asks for manual input of the username and password.
All I'm trying to do is authenticate from the header.
Any pointers would be very gratefully received.
I am getting an error when attempting to send a POST via AJAX from my own .html and .js files to localhost:8080. Upon submitting the request, the full error reads: "Access to XMLHttpRequest at 'http://localhost:8080/contact/new-message' from origin 'null' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status."
CORS is already enabled on my browser, so access is automatically "Access-Control-Allow-Origin : *", so this is a different from that error.
Is there a way to include an "ok" status in the header? Or is the problem arising from elsewhere? Any help is greatly appreciated. Here are some code snippets:
My JavaScript, which runs as part of a form-submission:
function submitMessageAJAXCall(inputName, inputEmail, inputMessage, inputRegion) {
$.ajax({
type: 'POST',
url: 'http://localhost:8080/contact/new-message',
data: JSON.stringify({
rbName: inputName,
rbEmail: inputEmail,
rbMessageText: inputMessage,
rbRegionId: inputRegion
}),
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
success: function() {
alert('Success!');
displayThankYouMessage();
},
error: function(jqXHR, textStatus, errorThrown) {
alert('Unfortunately that message did not go through.');
}
});
}
The Java code which recieves it:
#PostMapping("/new-message")
private ResponseEntity<HttpStatus> addNewMessage(#RequestBody RBNewMessage rbNewMessage) {
//validate message in service layer
boolean isRequestValid = contactService.validateNewMessageRB(rbNewMessage);
//is message is good, save it; else, return an error
if (isRequestValid == true) {
//create a new message
ContactMessage message = new ContactMessage();
//set message fields
message.setMyName(rbNewMessage.getRbName());
message.setMyEmail(rbNewMessage.getRbEmail());
message.setMessageText(rbNewMessage.getRbMessageText());
LocalDateTime timeOfMessage = LocalDateTime.now();
LocalDateTime timeWithoutNano = timeOfMessage.withNano(0);
message.setTimeStamp(timeWithoutNano);
int regionId = rbNewMessage.getRbRegionId();
Region region = regionService.getRegionById(regionId);
message.setRegion(region);
ContactStatus cs = contactStatService.getStatusById(1);
message.setContactStatus(cs);
//save message
contactService.save(message);
//return success
return new ResponseEntity<>(HttpStatus.OK);
} else {
//return error
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
}
And this is an example of a Postman request that is successful:
{
"rbName": "John Johnson",
"rbEmail" : "JohnJohnson#Email.com",
"rbMessageText" : "Hello there, this is my message.",
"rbRegionId" : 5
}
Add #CrossOrigin annotation (import org.springframework.web.bind.annotation.CrossOrigin) to the top of the controller class that is handling the request.
I have been trying about a week but I couldn't make a post request to get a result.
I tried a bunch of middlewares (exp: 'request', 'axios', 'reqclient','superagent etc..) but I couldn't make it.
Please provide me a simple post request with sending API key and body.
I also read all the documentation.
Please check below to see what I want :
*Authentication API key required.
*O-Auth Scopes trades
*Input One of: user_id + token or user_url is required.
here is my one of try :
const request = require('request-promise')
const options = {
method: 'POST',
uri: 'api-site.com/Offer/v1/',
headers: {
'User-Agent': 'Request-Promise',
'Authorization': 'Basic 123123asdasd123123'
},
body: {
user_url: "site.com/user/user1234123",
otherparams: "parameter"
},
json: true
};
request(options)
.then(function (response) {
Console.log(response);
})
.catch(function (err) {
console.log('Error ', err.message);
});
I am getting this output :
Error : 401 - {"status":401,"time":1540458426,"message":"API Key Required"}
I tried some other request post middle-wares and played with content-type (application/json. dataForm, x-www-form-urlencoded) or
changed the location of my API key from header to body or
tried my API key inside of auth{authorization: "API Key"}
tried much more.
the result didn't change. I got the same output or errors.
EDIT :
this is the link that I am trying to do but got stack :
check here
Solved !
Everything works great. Problem was I needed to send my API Key base64 string.
Buffer.from("your_api_key_value" + ":", "ascii").toString("base64")
In our Angular app, we need to parse response headers of some $http.
In particular we need to parse some X-prefixed response headers, for example X-Total-Results: 35.
Opening the Network tab of the browser dev tools and inspecting the resource relative to the $http request, I verified that the response header X-Total-Results: 35 is present.
in the browser, the X-Total-Results header is available, but cannot be parsed in the Angular $http.
Is there a way to access in $http the 'raw' response and write our custom parser for the header?
$http.({method: 'GET', url: apiUrl,)
.then( function(response){
console.log('headers: ', response.headers());
console.log('results header: ', response.headers('X-Total-Results'));
// ...
})
console output
headers: Object {cache-control: "no-cache="set-cookie"", content-type: "application/json;charset=utf-8"}
results header: null
The reason you can't read the header on JavaScript but you can view it on the developer console is because for CORS requests, you need to allow the client to read the header.
Your server needs to send this header:
Access-Control-Expose-Headers:X-Total-Results
To answer your question in the comments, The Access-Control-Allow-Headers does not allow wildcards according to the W3 Spec
Use $httpProvider.interceptors you can intercept both the request as well as the response
for example
$httpProvider.interceptors.push(['$q', '$injector', function ($q, $injector) {
return {
'responseError': function (response) {
console.log(response.config);
},
'response': function (response) {
console.log(response.config);
},
'request': function (response) {
console.log(response.config);
},
};
}]);
Update : You can retrive your headers info in call itself
$http.({method: 'GET', url: apiUrl)
.then( (data, status, headers, config){
console.log('headers: ', config.headers);
console.log('results header: ', config.headers('X-Total-Results'));
// ...
})
I have a simple ajax post to the server..
$(".invite-team-members-submit-btn").click(function() {
$.post("invite_team_member", { token: $("#token").val(), email: $("#email").val(), team: $("#team").val() })
.done(function (responseText) {
responseText = jQuery.parseJSON(responseText);
alert(responseText.response);
})
.fail(function (data) { alert("ERROR: " + data); })
.then(function () { alert("Something should happen."); });
});
The JSON returned looks like this...
{"response":"Person has been invited."}
My response header in the console looks like this...
Response Headers
Cache-Control max-age=0, private, must-revalidate
Connection close
Content-Type application/json; charset=utf-8
Date Wed, 22 May 2013 21:45:07 GMT
Etag "e5b5e12acbcc78372b2a861027b66c05"
Status 200 OK
Transfer-Encoding chunked
X-Request-Id d835ce021eff7733d67ebfcdd468bdf2
X-Runtime 0.007909
x-ua-compatible IE=Edge
In my console I see that it the server and returned the appropriate text, but I don't receive an alert in my browser. I'm just out of idea's on what's wrong. Has jQuery updated something that I'm missing?
You are using $.post incorrectly. You mean to use $.ajax and specify the type: "post" property.
$.post's first argument is the URL. In your case it's an object. I think that perhaps jQuery ends up using the current page URL to make a request instead (which is why you see one), but I can't be sure. You could rewrite this as:
$.post("invite_team_member", {data: data})
.done(function (responseText) { alert(responseText); })
.fail(function (data) { alert("ERROR: " + data); });
use $.ajax() then set the type to "POST"
Try this code:
mydata = "name=Jon&location=USA";
$.ajax({
type : 'POST',
url : 'myphp.php',
data : mydata
}).done(function(msg){
alert("DONE");
});