Axios request not sending payload when I use axios({...}); - axios

To me, this code is the same, however in Chrome Dev Tools, the first request has the payload set:
But the second doesn't. Any ideas?

Based on an example from Axios Github page, the data property contains the payload
// Send a POST request
axios({
method: 'post',
url: '/user/12345',
data: {
firstName: 'Fred',
lastName: 'Flintstone'
}
});
So, in your second request, you should change body to data

Related

A platform returns a POST method to an url and I want to retrieve the data to firestore

I want to retrieve the data from a third party platform that generates a POST call to an url that I can define. But I can only configure the url. I cannot configure the headers or the body of the POST action.
I want to store the JSON into a firestore collection.
The platform calls a POST action to a URL y can define, and that POST action has a JSON with the parameters I want to store.
In another post they directed me to the firestore API
https://stackoverflow.com/a/50061155/18276916
But there it is stated that the body of the POST action must have the following structure:
{
"writes": [
{
object (Write)
}
],
"labels": {
string: string,
...
}
}
The body of the POST action is defined in the third party aplication, and I cant modify it.
Is it posible to do this with Firestore, or is there another method I can use?
What would be the path of the url?:
https://firestore.googleapis.com/v1/projects/[my-project-id]/databases/(default)/documents/[my-collection-name]
Also, can I set the firestore rules to allow everyone to perform create actions so the call doesn't need to be authenticated
I found a solution that works
https://www.jeansnyman.com/posts/google-firestore-rest-api-examples/
With the following structure:
Url: https://firestore.googleapis.com/v1/projects//databases/(default)/documents/
Body:
{
fields: {
title: { stringValue: title },
category: { stringValue: category }
}
}
But here the body has its defined structure. I would need the url to accept:
{
title: title,
category: category
}

Axios: Access URL with serialised query string

Is there a way to access the full URL Axios makes a request to with the query
string params?
I am making a request with:
async function makeRequest(url: string, query: Record<string, unknown>): Promise<unknown> {
const params = querystring.stringify(query);
const response = await axios.request({
method: 'get',
url,
params,
});
return response.data;
}
Given the value for query { foo: 'bar', baz: 'bat' } and url of https://api.example.org, how can I access the full URL https://api.example.org?foo=bar&baz=bat?
There should be a request? property on the AxiosResponse object, which I was hoping would hold a reference to the URL, however this is always undefined in my testing.

Get all matching items using ids array form database

I can't receive list of items that matches with my array of ids.
This is PART of code in Angular component:
this.orderService.getSpecyficOrders(ids)
.subscribe(orders => { ...
Where ids is an array of
[{_id : ID },{_id : ID },{_id : ID },]
ID is "5235sd23424asd234223sf44" kind of string form MongoDB documents.
In angular service file I have imported:
Http, Headers, and import 'rxjs/add/operator/map';
Here is code in service in Angular:
getSpecyficOrders(ids){
return this.http.get('/api/ordersspecyfic', ids)
.map(res => res.json());
}
In express file I have require: multer, express,router,mongojs, db
And here is part of code in express, call to mongodb:
router.get('/ordersspecyfic', function(req, res, next){
var ids = req.body;
ids = ids.map(function (obj){ return mongojs.ObjectId(obj._id)});
db.orders.find({_id: {$in: ids}}, function(err, orders){
if(err){
res.send(err);
}
res.json(orders);
});
});
And I'm getting error:
Uncaught Response {_body: "TypeError: ids.map is not a function
&n…/node_modules/express/lib/router/index.js:46:12)↵", status:
500, ok: false, statusText: "Internal Server Error", headers:
Headers…}
Console.log in express file
is showing me that req.body is an empty object {}
As far as I know req.body is not an array, but I don't know if this is only problem with that code.
All others request of get single element, get all items etc. are working fine.
I just can't get this one working..
I assume you are trying to send ids to your server side with
return this.http.get('/api/ordersspecyfic', ids)
but http.get api doesn't work like that
get(url: string, options?: RequestOptionsArgs) : Observable
In order to send this data to your back-end you should use the post api
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
return this.http.post('/api/ordersspecyfic', ids, options)
post(url: string, body: any, options?: RequestOptionsArgs) : Observable
Source:https://angular.io/docs/ts/latest/api/http/index/Http-class.html
Two errors, backend and frontend.
Frontend error
You say this.http.get('/api/ordersspecific', ids);. This does nothing - or specifically, this only tries to get /api/ordersspecific. It doesn't send ids, your second parameter doesn't match any RequestOptions. In other words, your ids are ignored.
You'd want to append this as a query string. Check here how to add querystring parameters. But in short, it'd be something simple like:
return this.http.get('/api/ordersspecyfic?ids=<id1>&ids=<id2>...'
Backend error
You're reading stuff from body. It's a GET request, there should be no body. Read this from querystring:
router.get('/ordersspecyfic', function(req, res, next){
var ids = req.query.ids;
});

Non-standard REST API in Backbone js

I am building Backbone.js models backed by a legacy REST API. When I create a new resource on the server, rather than return the JSON of the newly created resource, it returns plain text of the id of the newly created resource, along with a relative URL in the Location header where the resource can be gotten.
For example, I POST:
{ "firstName": "Joe", "lastName": "Blow" }
to http://fakeserver.com/people and (on success) the body of the plain/text response might be: "1234". The status of the response is 201 and the Location header would be http://fakeserver.com/people/1234. If I GET from that Location URL, it will have
{ "id": 1234, "firstName": "Joe", "lastName": "Blow" }
How would I override the sync function on my model to accommodate this convention instead of the default Backbone.js conventions?
To clarify, there is no Backbone.js version of this yet - I am trying to create a new one. The old jQuery-only way of doing it was:
$.ajax({
type: 'POST',
url: submitURL,
data: $.toJSON(person),
success: function(data, status, request) {
showSuccessMessage();
closeDialog();
},
dataType: 'json',
contentType: 'application/json'
});
The details of the showSuccessMessage and closeDialog are unimportant - just to demonstrate that basically we are just ignoring the content of the response and throwing the original object away.
Handle the simple text response with parse:
http://backbonejs.org/#Model-parse
parse : function(response, options){
console.log(response, options);
var data = this.toJSON(): //current model to hash
data.id = response; <- assuming that response is a simple text plain id
return data;
}
You could also use sync to overwrite something in the ajax call(that is not supported in the options hash.
http://backbonejs.org/#Model-sync

MongoLab API Update: message: "Update object is missing."

Unable to update data in the data base. The above is a request link.
https://api.mongolab.com/api/1/databases/my-db/collections/my-coll/52f7b875e4b0e615e67f0a41?jsonbody=[{"_id":"52f7b875e4b0e615e67f0a41","like":"true"}]&apiKey=my_api_key
Got. 400 Bad Request error and message: "Update object is missing."
Or anyone can give an example to update mongodb via REST API in java would be very helpful.
Thanks.
It looks like you're missing the actual update spec, which should be the body of the PUT request. The MongoLab Data API docs include example of how to do that from jQuery, the key bits of which I've copied below for your convenience.
$.ajax( { url: 'https://api.mongolab.com/api/1/databases/my-db/collections/my-coll?apiKey=myAPIKey&q={"_id":1234}',
data: JSON.stringify( { "$set" : { "x" : 3 } } ),
type: "PUT",
contentType: "application/json" } );
Note that the $set update operator is not part of the url, but the body (which you specify in jQuery using the data field).