jQuery ajaxs CORS request - javascript

I am calling jQuery ajax request, at CORS resourse. Backend works on nginx, and there set OPTIONS hook and response with allowed all domains, and all request types. But unfortunatly i am getting error calback. On Chrome Network console i saw 204 answer on OPTIONS request. And I have never seen my original POST request.
var email = $('#your_email').val();
var sendData = {
issue: {
description: "email:" + email,
category_id: 1
}
};
$.ajax({
url: "https://domen/issues.json",
type: "POST",
beforeSend: function (xhr) {
xhr.setRequestHeader("Authorization", "Basic " + btoa("goodtry:goodtryq"));
xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("Content-type", "application/json")
},
data: JSON.stringify(sendData),
success: function (val) {
alert("Thanks you, we are going to contact you soon");
},
error: function (val) {
alert("Please check your internet connection");
}
});

So it is solved. I missed diagnostic message
Request header field Authorization is not allowed by Access-Control-Allow-Headers.
So helpful answer culd be found here:
https://stackoverflow.com/a/24556330/2835239

Related

Error sending AJAX POST request from local .html file to localhost:8080. CORS: "It does not have HTTP ok status."

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.

POST Request problems in JavaScript [duplicate]

This question already has answers here:
XMLHttpRequest cannot load XXX No 'Access-Control-Allow-Origin' header
(11 answers)
Closed 3 years ago.
I`m working on a project in JavaScript and basically what I want is to send a post request to my server in order to perform a login. So I do that as it fallows:
in Index.html
<input type="button" name="" value="Login" id="login" onclick=doLogin() onsubmit="return false">
and I have a user.js
function doLogin() {
let email = $('#emailLogin').val().trim();
if(email === ""){
email = null;
}
let password = $('#passwordLogin').val().trim();
if(password === ""){
password = null;
}
sendLoginRequest(email,password,getLoginSuccessHandler,getLoginErrorHandler);
}
function sendLoginRequest(email, password, successHandler, errHandler) {
localStorage.removeItem('auth');
localStorage.setItem('auth', btoa(email + ":" + password));
let data = {email: email, password: password};
jQuery.ajax({
type: 'POST',
url: getURL() + "user/login",
contentType: "application/json",
headers: { 'Authorization' : 'Basic ' + getAuth()
},
data: JSON.stringify(data),
dataType: "json",
accepts: "application/json",
success: function (data, status, jqXHR) {
successHandler(data);
},
error: function (jqXHR, message) {
errHandler(jqXHR.responseText.message);
}
});
}
So when I press the button the page will send an OPTIONS request not a POST request.
And in the console the message it printed like that:
HTTP403: FORBIDDEN - The server understood the request, but is refusing to fulfill it.
(XHR)OPTIONS - http://localhost:port/user/login
It's possible your server is throwing a CROSS Origin error, you need to enable CORS on your server by adding these flags in the response of your server.
headers.add("Access-Control-Allow-Origin", "*");
headers.add("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");
//If you have some custom headers please add below
headers.add("Access-Control-Allow-Headers", "X-Requested-With, Content-Type, {your-custom-header}");
If you quickly want to test your API & Login Flow you can use any of the plugins on chrome extention to allow CORS for you. However, this is not a permanent solution like the one given above.

AJAX request: Not enough or too many segments

I'm trying to do a POST request with AJAX and I'm getting the following error:
Error: Not enough or too many segments
I have this function to send AJAX request:
function sendAjaxRequest(type, url, params, callback, returnType = 'json') {
var token = token_admin;
var request = $.ajax({
url: url,
method: type,
data: params,
beforeSend: function(xhr) {
/* Authorization header */
xhr.setRequestHeader("Authorization", "BEARER " + token);
// xhr.setRequestHeader("X-Mobile", "false");
},
dataType: returnType,
contentType: 'application/json'
});
request.done(function(res) {
callback(res);
});
request.fail(function(jqXHR, textStatus) {
console.error(jqXHR);
callback({ err: true, message: "Request failed: " + textStatus });
});
}
And I'm using it like this:
var hostAPI = 'server_url';
var token_admin = 'some_token';
var params = {
"criteria": {
"lang.es_es.verb.parent": "abandonar"
}
}
sendAjaxRequest("POST", hostAPI + 'words/getByCriteria', JSON.stringify(params), function(response) {
console.log("------------");
console.log(response);
console.log("------------");
});
But it's always returning me this error, the most weird thing is that I tested this webservice in Insomnia like this:
{
"criteria": {
"lang.es_es.verb.parent": "abandonar"
}
}
And it returns all data properly. I'm pretty new with AJAX and I have no idea of what's happening here, why it works in Insomnia and not with Javascript AJAX? What am I doing wrong?
Thank you very much for your answers.
This error usually comes when your JWT token is malformed or invalid. Please note that you are passing it in headers
xhr.setRequestHeader("Authorization", "BEARER " + token);
Please ensure that the token is valid, and the API is capable of accepting it. Also, please try to change BEARER to Bearer. The latter can be a cause if the API is not ignoring the case while checking for the header value.

Bad Request Error when making AJAX request using JQuery-2.0.3

I'm not sure what is wrong with this request, but here is what is happening..
It appears the browser thinks I am making a cross-domain request, however I am making a request to the same page that the request comes from.
I call a function called search, and I am returned this in my google chrome dev console
EDIT:
The same thing happens when I load jquery-1.0.2.min.js
The server returns this: {"readyState":4,"status":404,"statusText":"error"}
Bad request search.js?1383509337:48
POST http://example.com/transaction/search jquery-2.0.3.js:7845
x.support.cors.e.crossDomain.send jquery-2.0.3.js:7845
x.extend.ajax jquery-2.0.3.js:7301
search search.js?1383509337:22
(anonymous function) search.js?1383422028:17
x.event.dispatch jquery-2.0.3.js:4676
y.handle jquery-2.0.3.js:4360
Function search()
function search(user, transactionDate, vendorField, amountField, accountField, departmentField, subDepartmentField, statusField, projectidField){
var url = "/transaction/search";
var ajax = jQuery.ajax({
type: 'POST',
dataType: 'json',
url: url,
data: {
user: user,
transactionDate: transactionDate,
vendorField: vendorField,
amountField: amountField,
accountField: accountField,
departmentField: departmentField,
subDepartmentField: subDepartmentField,
statusField: statusField,
projectidField: projectidField
},
beforeSend: function(data){
$('#searchSpinner').show();
console.log("Sending request");
},
success: function(data){
console.log("Successful request");
data = JSON.parse(data, true);
loadTransactions(data['response']['transactions']);
$('#searchSpinner').hide();
},
error: function(data){
console.log("Bad request");
$('body').html(JSON.stringify(data));
$('#searchSpinner').hide();
}
}).done(function(data){
console.log("finished");
$('#searchSpinner').hide();
});
}
Turns out the problem wasn't with the AJAX request, but a bad formed MySQL query was taking up too much resource time and the page time'd out.

Cross domain jquery ajax request with custom headers and request body as JSON string

I need to create a JSON ajax request from another domain. after I think I got over the cross domain issues, here is where I stuck:
I need to add my custom "myCustomHeader" header - that's easy from a server, but seems to be much more complicated from the client...
We added them
$.ajax({
type: 'POST',
data: put the results of your header request here,
url: 'http://server.com/service',
beforeSend: function (xhr) {
xhr.setRequestHeader('myCustomHeader', '1')
},
success: function(data) {
alert('success.');
}
});
This generates a preflight header with the headers I wanted, without the values (CSV), but they do not appear in the header of the request itself (as myCustomHeader=X)...
You can use CORS for this purpose.
Example code:
jQuery.support.cors = true;
function CrosDom_ajax(url) {
if (window.XDomainRequest
&& $.browser.msie
&& $.browser.version < 10) {
xdr = new XDomainRequest();
if (xdr) {
xdr.onload = function () {
alert(xdr.responseText);
};
xdr.open("get", url);
xdr.send();
}
}
else {
$.ajax({
url: url,
success: function (response) {
},
error: function (data) {
}
});
}
}
Also you need to Write the following code in server side, to allow cross domain access
Response.AppendHeader("Access-Control-Allow-Origin", "*");

Categories