Problem Posting json data to API using Axios in Vue JS - javascript

I am trying to create a Axios request where i will post json data. The format of the data will be
{"qBody":"aaa","qAnswer":"bbb","qOptions":[],"qType":"GAP","qClass":6,"qSubject":1,"qChapter":1,"qCreatorid":1,"qCreatorrole":"admin"}
But it is posting as
{"data":{"qBody":"aaa","qAnswer":"bbb","qOptions":[],"qType":"GAP","qClass":6,"qSubject":1,"qChapter":1,"qCreatorid":1,"qCreatorrole":"admin"}}
Here is my code snippet:
var data = {
"qBody" : question,
"qAnswer" : trueFalseAnswer,
"qOptions" : qOptions,
"qType" : questionCategory,
"qClass" : className,
"qSubject" : subjectName,
"qChapter" : chapterName,
"qCreatorid" : qCreatorid,
"qCreatorrole" : qCreatorrole
};
const newData = JSON.stringify(data)
this.$axios.post("http://128.199.192.87:8081/api/v1/questions/add",{
newData
},{
'Content-Type': "application/json"
}).then((response)=>{
console.log(response)
})
How can I make the format correct? Thanks in advance

What you are console.log()-ing is not what you're sending. It is the response that's getting back from the server. If you want to log what you're sending, use:
console.log(newData);
... just before making the POST request.
Most likely, you don't need to stringify the request.
What you're seeing in the console is the server response. According to the response-schema in their documentation, the server's response data is placed in the .data property of the response object.
So, apparently, the server sends back the same data. With most servers, this means no error has occurred.
In fewer words, you are not sending your data wrapped as { data: ... }. If you were, you would be getting back: { data: { data: ... } }

Related

Getting None values for POST request (via the Axios library) sent to Python/Django

I am building a web app with Django/Python and trying to send data to a controller via a POST request using the Axios library (within Vue.js code).
The POST QueryDict seems to be empty and I can't see why that is happening:
changeCountry: function(e, id){
console.log("Let's change the country")
console.log(e.target.value) // is printing correctly
console.log(id) // also printing correctly
axios({
method: 'post',
url: '/template/country',
data: {
id: id,
country: e.target.value
},
headers: {
'X-CSRFToken': "{{csrf_token}}"
}
})
.then(function (response) {
alert(response.data); // this is returning what I expect
})
.catch(function (error) {
console.log(error);
})
},
The Python method looks like this:
def update_template_country(request):
pprint(request.POST) # prints an empty QueryDict
id = request.POST.get('id')
country = request.POST.get('country')
print(id, country) #prints None None
return HttpResponse("The country is changed") # this is being returned back to the client
The console.log messages at the top print what I expect and since there is no error I am assuming the CSRF header token is fine. Have I missed something obvious or misunderstood how this is working?
EDIT: looking at the Chrome Network tab, it seems the data is being 'POSTed' correctly:
It shows this:
{"id":"593ff2270098e6e8d3292b60","country":"US"}
and that's what I expect, so I suspect the issue is with Django. But I can't see what that might be.
Write your python POST request like this:
def update_template_country(request):
data = json.loads(request.body)
id = data["id"]
country = data["country"]
'''Any other function you want to perform'''
return HttpResponse(json.dumps({'message':'The country is changed'},status=200)
Basically the problem is with the format of POST request, Django is not able to parse it properly that's why when you print the POST request it return an empty dictionary.

Node js server not receiving data from angularjs

I have a data at angularjs client. when i send the data to server using $http.post, i am not able to read data at server. I dont understand where i have gone wrong ?
This is the angular code:
var data = $.param({
id:$scope.user_id,
});
alert(JSON.stringify(data));
$http.post('/getdetails',data)
Here is the node js server code:
app.post('/getdetails',function(req,res){
console.log(req.body);
console.log(req.body.id);
});
output at server log:
{}
undefined
I am not concerned about data i send, i am only concerned whether it is readable at server or not.
Thanks !
You are trying to serialise your data using $.param() which is used only in the GET method and not in post. Just send your JSON data directly to nodeJs like this :
var data = {
id:$scope.user_id,
};
$http.post('/getdetails',data)
In you headers specify :
"Content-Type" : "application/json"
So the final request will be like this :
$http.post('/getdetails',data,{headers : {"Content-Type" : "application/json"}})

python3.5 aiohttp, request post, json format and 405 errors

I finally sign up because I have no more idea for my problem.
I use asyncio and aiohttp for my back-end part and javascript for the front-end part. But I stuck with a 405 error. (I precise I am a beginner with theses libraries)
I wish retrieve a json from a post request. Here the javascript function:
function postJson (data){
$.ajax({
url : 'http://localhost:8080/postJson',
type : 'POST',
dataType : 'json',
contentType : 'application/json',
data : data, //data are ready at json format, I do not think I need to use JSON.stringify ? I does not change anything to the error anywhere
success : function(code_html, statut){
console.log("success POST");
},
error : function(resultat, statut, erreur){
console.log("error POST");
}
});
}
and the python code:
async def postJson(request):
data = await request.post()
#some code
return Response()
#asyncio.coroutine
def init(loop):
app = Application(loop=loop)
app.router.add_route('POST', '/postJson', postJson)
handler = app.make_handler()
srv = yield from loop.create_server(handler, '127.0.0.1', 8080)
print("Server started at http://127.0.0.1:8080")
return srv, handler
loop = asyncio.get_event_loop()
srv, handler = loop.run_until_complete(init(loop))
try:
loop.run_forever()
except KeyboardInterrupt:
loop.run_until_complete(handler.finish_connections())
With this code I get a 405 error. Here a bite of what says firebug about the request:
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 // so json is not in the list.
however, if I take back the line contentType : 'application/json' in my javascript file, it works (but the request send a object called MultiDictProxy and I don't understand how to use the function json() from aiohttp.web package (here).
I really need to get a json object. Someone could help me?
I find the solution. I post the conclusion here for people who could be interested:
python side:
replace the line app.router.add_route('POST', '/postJson', postConf) by
app.router.add_route('POST', '/postJson', postConf, expect_handler = aiohttp.web.Request.json)
in the postJson method:
replace data = await request.post() by data = await request.json()
and on javascript side:
data : JSON.stringify(data)
with this, my method works.
Your example works fine except two things:
#asyncio.coroutine and async with are mutually exclusive
postJson() must return response instance, not None

AngularJS Factory : JSon and Authorization

I have a problem with my AngularJS factory. Actually, I have to make a request which includes a JSon variable, and it has an Authorization header.
It looks like this :
createEvent:function(event){
return $http.get(url, {
headers: { 'Authorization' : token }
})
}
The event variable is a JSon object, and I want to get it in the $http.get function as I have a Validator in the backend which tests this json file.
Is there any way for me to pass this variable here ?
Thanks !
It looks strange that you use the 'GET' method to send data.
createEvent:function(event){
return $http.post(url, {
headers: { 'Authorization' : token },
data : event
})
}
seems better.
Also check that your content type is correctly set.
You can pass event json as data.
createEvent:function(event){
return $http.get(url, {
headers: { 'Authorization' : token },
data : event
})
}
You can simply send the data using params object when using GET http method. Other thing is if you are sending JSON string you need to JSON.parse it.
...
$http.get(url, {
headers: {'Authorization': token},
params: event // or "JSON.parse(event)" if event is json string
});

Ajax post request string data instead of object

Similar to this question I need to send a string as data in a post request.
Unlike that one, I can't use an object because I have repeated items. As you can see in my sample data sn1, sn2 and sn3 are repeated several times on different datetimes.
Sample data:
&sn3=2013-2-4T12:43:52&sn3=2013-2-4T12:43:55&sn1=2013-2-4T12:43:59&sn1=2013-2-4T12:44:0&sn2=2013-2-4T12:44:0&sn3=2013-2-4T12:44:2&sn2=2013-2-4T12:44:3&sn3=2013-2-4T12:44:19&sn3=2013-2-4T12:44:19&sn3=2013-2-4T12:44:19&sn2=2013-2-4T12:44:19&sn3=2013-2-4T12:44:21&sn2=2013-2-4T12:44:22&sn2=2013-2-4T12:46:39&sn3=2013-2-4T12:46:42&sn2=2013-2-4T12:46:44&sn2=2013-2-4T12:46:45&sn2=2013-2-4T12:46:46&sn2=2013-2-4T12:47:27&sn2=2013-2-4T12:47:27&sn2=2013-2-4T12:49:44&sn2=2013-2-4T12:50:21&sn2=2013-2-4T12:52:21&sn2=2013-2-4T12:52:24&sn2=2013-2-4T12:57:35&sn3=2013-2-4T12:57:38&sn3=2013-2-4T12:57:39&sn2=2013-2-4T12:57:39&sn2=2013-2-4T12:57:40&sn3=2013-2-4T12:57:46&sn3=2013-2-4T13:21:30
I tried using the following
console.log(screens); //logs my sample data posted above.
$.ajax({
url : url,
type: "POST",
dataType : 'text',
data : screens,
success : function(data) {
console.log("sucessfull sending:")
console.log(data);
},
error : function() {
console.log('failed');
}
});
But it always triggers failed.
Can I send it as a string? If not, how can I send multiple items with the same key?
console.log(screens); //logs my sample data posted above.
$.ajax({
url : url,
type: "POST",
dataType : 'text',
data : {screens:screens},
success : function(data) {
console.log("sucessfull sending:")
console.log(data);
},
error : function() {
console.log('failed');
}
});
See data : {screens:screens},, if you do something like that, on server you will be able to get it like: screensString = Request["screens"]. After that, screensString will contain a single string with all screens.
When you don't specify contentType in the ajax options, your request will default to 'application/x-www-form-urlencoded; charset=UTF-8'.
However, when your post data is just text, you should make the server aware of that fact by specifying a contentType 'text'.
As opposed to the contentType, the dataType specifies the type of response data that you expect back from the server.
I think what you need is to use [] in your parameters.
instead of sending &sn3= multiple times (which is rewriting itself) send it as an array like this &sn3[]=
if you are getting this data from an form input use name="sn3[]" and if this is the case, I would recommend you use $('#yourform').serialize() as data sent

Categories

Resources