Using a normal html form, I can add a new task by sending POST request to /api/tasks/insert/
POST data includes $name and $description of the task.
However, when I use Angular to push the data to REST API in php, only a POST request is sent and an empty row is created in the database.
This means that the POST variables are not being passed i.e. name and description.
What am I doing wrong?
I have been stuck at this for the last few hours now. I have checked countless tutorials and am pretty sure of the syntax. My backend REST api in PHP works fine.
var res=$resource('http://localhost/api/tasks/insert/',{},
{
createTask:{method:'POST'}
});
postData={name:"Hello",description:"DescBaby"}
res.createTask({},postData);
//res.createTask(postData); tried this also, but doesn't work
Another variation that I tried based on an comment was this:
res.createTask({name:"TestName", description:"descBaby"}).$promise.then(function(value)
{
console.log("Success"); //I get success in console.
},function(errResponse)
{
console.log("Error");
});
Angular Does not give me any errors. Just sends a blank POST request to the url.
EDIT:
I checked in the network pane in Chrome whether the data was sent or not and as it turns out it is being sent.
However, in the response it's showing this :
Undefined index: name in XYZ.php line ABC.
The line pointed above is the following line in my PHP:
$obj->InsertTask($_POST['name'],$_POST['description']);
Thanks to a friend of mine, I finally got the code running. The problem wasn't with my Angualar Code but with php code.
As it turns out I cannot read POST data as $_POST[].
file_get_contents should be used in such cases as data is sent through a JSON payload and not through request parameters!
Here's how I got it running : Angularjs $http.post, passing array to PHP
Did you look at the network tab of debugger? You can check if valid data was sent to server. If it was ok this is not JS or Angular question. On the first look it seems that you have valid code for angular. Just in case check if you have set proper ajax headers.
"X-Requested-With": "XMLHttpRequest"
Does other AJAX calls work for you?
Try this (and create a factory to follow the best practices):
Service
services.factory("Tasks", function($resource) {
return $resource('http://localhost/api/tasks/insert/', {}, {
createTask: {method:'POST', params: {name:"Hello",description:"DescBaby"}}
})
});
Controller
Tasks.$createTask();
Related
I am using react-admin framework and I am trying to get error status code (404,500), which I would be saving to some variable for later usage. For example, when I try to create an user that has same e-mail address as already created user, the server wont allow this operation and the request fails with status code 500.
I need that status code to save to variable and work with it later.
Does react-admin offer this?
So far I have tried this simple code in my custom DataProvider, but when logging it to console, it returns undefined.
const status = params.message.status;
I wasn't able to find any other solution that I would fully understand.
Any ideas how to solve this?
Thank you in advance.
Basically this is what are you looking for:
https://developer.mozilla.org/en-US/docs/Web/API/Response/status
First of all, you actually need to request some data from the server in order to get the response.status code.
The most simple example would be this based on the link I listed before:
var myRequest = new Request(options.body); //depends on what do you want to request
fetch(myRequest).then(function (response) { //gets the response from server
console.log(response.status, 'status'); // this returns the status value
});
This should return the response.status code.
I'm trying to post some data to a Python backend that i made with Flask. I'm using SuperAgent in a React component. For some reason i keep getting HTTP error 400.
I've read many posts about similar problems using JQuery and flask. The solution there is to set the contentType the same way i have and also JSON.stringify the data. I've tried stringify but it doesn't change anything. Still getting an HTTP 400.
Any ideas?
JS code:
request.post(link)
.set('Content-Type', 'application/json; charset=utf-8')
.send({tag: 'tag1', comment: 'Cool'})
.end(function(err, res){
console.log(res);
});
Python function/endpoint:
#app.route('/api/leavecomments', methods=['POST'])
def comment_to_photos():
comment = request.form['comment']
print(comment)
tag = request.form['tag']
...
So the issue for anybody else that has this problem, they need to use method named get_json which will have the values being passed to it in JSON format. In the case of the code above it was looking for those values as a query string post parameters, which is typically sent via form posts. In the case of an AJAX JSON post, the data exists inside the request.body.
For more information check out...
http://flask.pocoo.org/docs/0.10/api/#flask.Request.get_json
I'm just following tutorials and figuring out how to handle get requests in NodeJS.
Here are snippets of my code:
NodeJS:
router.get('/test', function(request, response, next) {
console.log("Received Get Request");
response.jsonp({
data: 'test'
});
});
Angular:
$http.get("http://localhost:3000/test").
success(function(response) {
alert("OK");
}).
error(function(response) {
alert("FAIL");
});
If I try to access the link directly # localhost:3000/test, I'm able to receive the JSON message correctly. But when I use angularJS $http call, the request always fails and I'll find this error in the network inspector (Response)
SyntaxError:JSON.parse:unexpected end of data at line 1 column 1 of
the JSON data
The reason for that is because the response is empty but the response code is 200 in both cases.
I've tried searching for hours but maybe someone can enlighten me on this?
you could try and send
res.send('test')
and then on your http request you can use 'then'
$http.get("http://localhost:3000/test").then(function(res) {
console.log(res);
})
unlike success, then will give you a complete object (with 'test' - string as res.data)
success will bring you only the data;
then will bring you the whole object (with the status and such)..
now about that jsonp .. it's used to override a json response. you could simply use 'res.json({data: 'test'})' and it should also work for you..
hope it helps
You're using jsonp in node, which you probably don't need to. This adds extra characters to the response and so the JSON parser fails to parse (that's what the error is telling you, the JSON is malformed)
Try changing the server to look like
response.json({
data: 'test'
});
If you look in the Network pane of the developer tools, you should be able to see the raw response. It should look something like:
{"data" : "test"}
I am having a serious issue with Angularjs and jQuery with this particular REST API. I am not in the same domain as said API, and can get the data back, however I am getting a "SyntaxError: invalid label "name" :{" error.
If I were to do something like $http.get or $.get I get a timeout after 10 seconds. However, if I use jsonp with either library I will see in Firebug that the data is returned in the net tab, however I get the error above in the console tab. After doing some research, I have seen plenty of people having issue with the API (a Jive product) and this specific line of text that is returned along with the JSON. The response looks something like this:
throw 'allowIllegalResourceCall is false.';
{"name":{ "givenName": "xxx"}}
The big problem is the first "throw" line. I have tried a bunch of ways to remove that line but I haven't found the proper way to do it. I apologize for not being able to provide a code sample, but if there is any way to get this work in Angularjs or jQuery, I will take it. I don't know if the answer lies in Angularjs interceptors, or transformResponse.
Any help that can be provided will be appreciated.
Thank you
AngularJs allows you do define the methods for transforming the http response data (so you can remove the first line of the response data). You can do this either for a single request or add a httpInterceptor.
Single request:
$http.get('...', {
transformResponse: $http.defaults.transformResponse.unshift(function(data) {
// Remove first line of response
data.split("\n").slice(1).join("\n")
}
});
HttpInterceptor
.config(['$httpProvider', function($httpProvider) {
$httpProvider.interceptors.push(function() {
return {
'request': function(config) {
config.transformResponse.unshift(function(data) {
return data.split("\n").slice(1).join("\n")
})
return config;
}
}
})
}])
Plunker: http://plnkr.co/edit/6WCxcpmRKxIivl4yK4Fc?p=preview
I'm switching from jquery $.ajax, which was working fine, to using AngularJS $http.put to access a restful API.
I can make an API call, but the PUT data isn't getting sent - so my API sees a PUT request with an empty data object, which should contain a JSON string -> data.values = 'a json structure'
$http.put(
$rootScope.api_url,
{
values: jsonifiedValues
},
{
headers: {
apihash: sha256hash
}
}).success(function(data,status,headers,config){
// handle success
}).error(function(data,status,headers,config) {
// handle failure
});
I've not used AngularJS's $http before, but when I dump out the data in my PHP api it's just empty. this is how I'm pulling it from the request in the PHP:
parse_str(file_get_contents('php://input'), $put_vars);
$arr_req_data = $put_vars['values'];
In my API if the apihash sent from the request doesn't match the sha256 hash built on the PUT values, it fails.
This is working in JQuery, just failing now I've switched to $http. I'm not sure why the PUT data seems to be empty.
The return value from file_get_contents('php://input') will be a JSON string (provided everything got sent), so parse_str is not the right function to handle that data.
Instead use json_decode.
Also there is no need to send jsonified values, it will just make things more complicated as you'll have to use json_decode twice.