Can't set Access-Control-Allow-Origin request header - ajax

I making an AJAX request to the food2fork api and can't get by the No 'Access-Control-Allow-Origin' header is present error. I've tried setting the header in beforeSend and setting crossDomain: true but it didn't work.
This is my AJAX call:
$.ajax({
type: "GET",
dataType: 'json',
url: url,
crossDomain: true,
beforeSend: function(xhr) {
xhr.setRequestHeader("Access-Control-Allow-Origin", "*");
},
success: function(data){
console.log('in ajax json call');
console.log(data);
$('#info').html(JSON.stringify(data));
}
});
I tried setting the request header server side in node express.js with:
router.get('/test', cors(), function(req,res)
{
res.set("Access-Control-Allow-Origin", "*"); //set header here
res.render('exampleSearch', {title: 'FM | Test'});
});
Cors is an npm package that sets cross-reference permissions but didn't help me solve the problem.
Can you tell me what I'm doing wrong?

Client-side request doesn't work in this case. I had to do the request server side:
router.post('/test', function(req,res){
var callback = function(response){
var str = '';
//another chunk of data has been recieved, so append it to `str`
response.on('data', function (chunk) {
str += chunk;
});
//the whole response has been recieved
response.on('end', function () {
var recipes = JSON.parse(str);
//do something with recipes
});
}
var options = {
host: "food2fork.com",
path: "/api/search?key=[myKey]&q=" + ingredients
};
http.request(options,callback).end();
});
Used code from nodejitsu.com

Related

Laravel 5.4 not able to parse FormData javascript object sent using Jquery Ajax

Lately I've been trying to solve an issue with no luck, basically I'm trying to submit a form to the server using AJAX, the form has files, so I'm using the FormData javascript object in JQuery 1.12. The data arrives to the server but in I way I don't know how to format it.
This is my AJAX function:
function saveMenu(id){
var formElement = document.getElementById("menu-form");
var formData = new FormData(formElement);
formData.append('_method', 'PUT');
$( "#form-wrapper" ).toggleClass( "be-loading-active" );
$.ajax({
type: 'PUT',
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
url: "{{url('myUrl')}}",
data: formData,
enctype: 'multipart/form-data',
processData: false,
success: function(response) {
toastr.success('Yai! Saved successfully!')
},
error: function(response) {
toastr.error('Oh oh! Something went really wrong!')
},
complete: function() {
$( "#form-wrapper" ).toggleClass( "be-loading-active" )
}
});
}
and when I perform a dd($request->all()); in my controller I get something like this:
array:1 [
"------WebKitFormBoundaryRCIAg1VylATQGx46\r\nContent-Disposition:_form-data;_name" => """
"_token"\r\n
\r\n
jtv4bnn8WQnP3eqmKZV3xWka2YOpnNc1pgrIfk0D\r\n
------WebKitFormBoundaryRCIAg1VylATQGx46\r\n
Content-Disposition: form-data; name="blocks[43][title]"\r\n
\r\n
...
Things I've tried:
Set the HTTP verb to POST. Same result.
Set the AJAX contentType: false, contentType: application/json. Empty response.
Remove enctype: 'multipart/form-data'. Same response.
Any help is appreciated.
This fixed it for me
data: form_data,
contentType: false,
processData: false,
processData: false prevents jQuery from parsing the data and throwing an Illegal Invocation error. JQuery does this when it encounters a file in the form and can not convert it to string (serialize it).
contentType: false prevents ajax sending the content type header. The content type header make Laravel handel the FormData Object as some serialized string.
setting both to false made it work for me.
I hope this helps.
$('#my-form').submit(function(e) {
e.preventDefault();
var api_token = $('meta[name="api-token"]').attr('content');
form_data = new FormData(this);
$.ajax({
type: 'POST',
url: '/api/v1/item/add',
headers: {
Authorization: 'Bearer ' + api_token
},
data: form_data,
contentType: false,
processData: false,
success: function(result,status,xhr) {
console.log(result);
},
error: function(xhr, status, error) {
console.log(xhr.responseText);
}
});
});
also remember to use $request->all(); $request->input() excludes the files
I've been trying to debug that for 2 hours and i found out that method PUT is not working with formData properly.
Try changing
type : "PUT"
into
method : "POST"
Then change your method on your backend from put to post and you'll see the difference.
I used below codes to test it
$("#menu-form").submit(function (){
var fd = new FormData();
fd.append('section', 'general');
fd.append('action', 'previewImg');
fd.append('new_image', $('.new_image')[0].files[0]);
$.ajax({
method : 'POST',
headers: {
'X-CSRF-TOKEN': '{{ csrf_token()}}'
},
url: "{{url('upload-now')}}",
data : fd,
contentType: false,
processData: false,
success: function(response) {
console.log(response);
},
});
return false;
});
And in my controller
public function test(Request $request){
dd($request->all());
}
Ill try to research more about this issue.
Laravel 7,
if use method PUT in ajax, you can follow
1. change method method: 'PUT' to method: 'POST'
2. add formdata.append with _method PUT like this example :
$('#updateBtn').click(function(e){
e.preventDefault();
var frm = $('#tambahForm');
frm.trigger("reset");
$('.edit_errorNama_kategori').hide();
$('.edit_errorGambar').hide();
var url = "/pengurus/category/"+$('#edit_id').val();
var formdata = new FormData($("#editForm")[0]);
formdata.append('_method', 'PUT'); //*** here
$.ajax({
method :'POST', //*** here
url : url,
data : formdata,
dataType : 'json',
processData: false,
contentType: false,
success:function(data){
if (data.errors) {
if (data.errors.nama_kategori) {
$('.edit_errorNama_kategori').show();
$('.edit_errorNama_kategori').text(data.errors.nama_kategori);
}
if (data.errors.gambar){
$('.edit_errorGambar').show();
$('.edit_errorGambar').text(data.errors.gambar);
}
}else {
frm.trigger('reset');
$('#editModal').modal('hide');
swal('Success!','Data Updated Successfully','success');
table.ajax.reload(null,false);
}
},
error: function (jqXHR, textStatus, errorThrown) {
alert('Please Reload to read Ajax');
console.log("ERROR : ", e);
}
});
});
its works for me
Finally I gave up trying to make it work and tried a more vanilla approach, I still don't know the reason why the request is formated like that, but the XMLHttpRequest() function works perfectly and the migration is not a big deal.
The equivalent of the function I posted about would be:
function saveMenu(action){
var formElement = document.getElementById("menu-form");
var formData = new FormData(formElement);
formData.append('_token', $('meta[name="csrf-token"]').attr('content'));
var request = new XMLHttpRequest();
request.open("POST", "{{url('myUrl')}}");
request.send(formData);
request.onload = function(oEvent) {
    if (request.status == 200) {
      toastr.success('Yai! Saved successfully!');
    } else {
      toastr.error('Oh oh! Something went really wrong!');
}
$( "#form-wrapper" ).toggleClass( "be-loading-active" );
  };
}
Bit late, but;
This will solve your problem;
var formData = new FormData(document.getElementById('form'));
console.log(...formData);
var object = {};
formData.forEach(function (value, key) {
object[key] = value;
});
Then you can send this object to the server. This is much more readable and works great.
OR
You can simply send this directly;
JSON.stringify(Object.fromEntries(formData));
This is the newer approach.
And don't give up :-)

call server-side REST function from client-side

In the case, on the server side have some archive restApi.js with REST functions. My REST functions works fine, i test with Prompt Command.
In my client side have some archive index.ejs, And I want to call with this file.
My restApi.js: Server-side
var Client = require('./lib/node-rest-client').Client;
var client = new Client();
var dataLogin = {
data: { "userName":"xxxxx","password":"xxxxxxxxxx","platform":"xxxx" },
headers: { "Content-Type": "application/json" }
};
var numberOrigin = 350;
client.registerMethod("postMethod", "xxxxxxxxxxxxxxxxxx/services/login", "POST");
client.methods.postMethod(dataLogin, function (data, response) {
// parsed response body as js object
// console.log(data);
// raw response
if(Buffer.isBuffer(data)){
data = data.toString('utf8');
console.log(data);
re = /(sessionID: )([^,}]*)/g;
match = re.exec(data);
var sessionid = match[2]
console.log(sessionid);
openRequest(sessionid, numberOrigin); // execute fine
}
});
function openRequest(sessionid, numberOrigin){
numberOrigin+=1;
var dataRequest = {
data: {"sessionID":sessionid,"synchronize":false,"sourceRequest":{"numberOrigin":numberOrigin,"type":"R","description":"Test - DHC","userID":"xxxxxxxxxx","contact":{"name":"Sayuri Mizuguchi","phoneNumber":"xxxxxxxxxx","email":"xxxxxxxxxxxxxxxxxx","department":"IT Bimodal"},"contractID":"1","service":{"code":"504","name":"Deve","category":{"name":"Developers"}}} },
headers: { "Content-Type": "application/json" }
};
client.post("xxxxxxxxxxxxxxxxxxxxxxxxx/services/request/create", dataRequest, function (data, response) {
// parsed response body as js object
// console.log(data);
// raw response
console.log(data);
});
}
My index.ejs: Client side
<html>
<head> ------------- some codes
</head>
<meta ------- />
<body>
<script>
function send() {
$.ajax({
type: "POST",
url: "restApi.js",
data: '{ sendData: "ok" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
alert("successful!" + result.d);
}
});
}
</script>
<script src="restApi.js"></script>
</body>
</html>
I've try see others examples but does not work (Ajax).
And I need to know how to solved this, if have other Best practice for it, please let me knows.
In my console (Chrome) show if I call the ajax function:
SyntaxError: Unexpected token s in JSON at position 2 at JSON.parse (<anonymous>) at parse (C:\xxxxxxxxxxxxxxxxxxxxxxxxx\node_modules\body-parser\lib\types\json.js:88:17) at C:\xxxxxxxxxxxxxxxxxxxxxxxxx\node_modules\body-parser\lib\read.js:116:18
And if I click (BAD Request) show:
Obs.: Same error than app.js, but app.js works fine.
Cannot GET /restApi.js
In the case the file restApi.js Is a folder behind the index.
Folder:
Obs.: public folder have the index.ejs
Your problem is bad url. In case if you have fiule structure like this you have to point as shown in image
Based on the error I think the data you are posting via AJAX is not in correct syntax.
Change function send() as following.
function send() {
var obj = { "sendData" : "ok" };
$.ajax({
type: "POST",
url: "restApi.js",
data: obj,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
alert("successful!" + result.d);
}
});
}
This should resolve the error you are facing.
Try this now...
function send() {
var obj = {
sendData : "ok"
};
$.ajax({
type: "POST",
url: "Your url",
data: obj,
dataType: "json",
success: function (result) {
alert("successful!" + result.d);
},
error: function (error) {
console.log("error is", error); // let us know what error you wil get.
},
});
}
Your url is not pointing to js/restapi js.
and what code do you have in js/restapi js?
if your action page is app js you have to put it in url.
url:'js/restapi.js',

Access-Control-Allow-Origin' header is present on the requested resource. error

My ajax call is as follows
var data = {};
data.name = name;
data.phone = phone;
data.address=address;
$.ajax({
type: 'POST',
data: JSON.stringify(data),
contentType: 'application/json',
url: 'http://localhost:5000/endpoint',
success: function(data) {
console.log('success');
console.log(JSON.stringify(data));
}
});
and I am using node-js express server
and my server code is
app.post('/endpoint', function(req, res){
var obj = {};
console.log('body: ' + JSON.stringify(req.body));
res.send(req.body);
});
app.listen(5000);
I have tried the other solutions posted but I still keep getting this error
Response to preflight request doesn't pass access control check: No Access-Control-Allow-Origin header is present on the requested resource. Origin http://localhost:3000 is therefore not allowed access.
What do I need to do ?
Before your routing on your server, add :
app.all('/*', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
});
You can replace the * with the URL of authorized domains.
More informations : https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS

Http Post request in Angular JS

We are new to angular js.
We tried http request using $http.get it is working fine. But in post request it is creating an issue, it comes to success and show bad parameter error code 103.
Same we have tried in ajax request using $.ajax({}), and it is working fine.
I have also paste my code.
Can anyone help us out?
mainApp.controller('registrationCtrl', function($scope, $location, $http) {
$scope.registration = function() {
console.log("registration called");
var ws_url = "http://apparelinindia.com/selfiestandoff/WebServices/register";
var request = $http({
method: "post",
url: ws_url,
data: {
user_email: $scope.email,
user_password: $scope.password
},
dataType: 'json',
headers: {
'Content-Type': 'application/json'
}
});
request.success(function(data) {
console.log("Success" + data);
});
request.error(function(error) {
console.log("Success" + JSON.stringify(error));
});
};
});
You can use http Post in following way:
var request = $http.post(ws_url, {
user_email: $scope.email,
user_password: $scope.password
});
The name of the http method should be written in uppercase. Also, the property datatype is not awaited by $http, you should remove it:
var request = $http({
method: "POST",
url: ws_url,
data: {
user_email: $scope.email,
user_password: $scope.password
},
headers: {
'Content-Type': 'application/json'
}
});
Note, in the above call to $http you are setting the header 'Content-Type': 'application/json'. But this header is automatically injected by $http (see $http documentation), therefore you can remove it, and use the short syntax:
var request = $http.post(ws_url, data);
with data equals to:
{
user_email: $scope.email,
user_password: $scope.password
}
Are You Getting this error ??
{"status":false,"error":{"code":"103","message":"Required Parameters not found"}}
If Yes, Its Not your Problem Contact the Web service provider.
Ask him to give the valid parameter

Ajax call returns nothing for secured sites URL,How to access secured sites in ajax?

function loadMessages(){
$.ajax({
url :"https://www.yammer.com/api/v1/search.json?search=java",
async: false,
dataType: "json",
crossDomain: true,
success : function (data) {
alert(data);
var htmldata = "";
for(var cntr=0;cntr<data.messages.messages.length;cntr++){
htmldata += "<tr><td>"+data.messages.messages[cntr].content_excerpt+"</td></tr>"
}
alert("no of msgs"+data.messages.messages.length);
$("#text tbody").append(htmldata);
return data;
}
});
}
XMLHttpRequest cannot load https://www.yammer.com/api/v1/search.json?search=java. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8002' is therefore not allowed access. The response had HTTP status code 401.

Resources