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.
Related
Is there something I can do to prevent axios from renaming my FormData field name when it is an array.
For example:
I have an array of images I am posting using the field name of images. When I post this, I notice in the payload of my browser the field becomes multiple fields, i.e. it becomes images.0 and images.1.
In other words it looks like axios is renaming the field and making multiple fields with names like images.N.
Is there any way to avoid this renaming? On the server side I am using node with Nestjs and multer.
My Nestjs controller function expects a field name images but it throws an "unexpected field" error because axios renames the fields to images.0 and then images.1.
NestJS controller function that fails (note the field name):
#Post()
#UseGuards(AuthGuard('jwt'))
#UseInterceptors(FilesInterceptor('images', 30, { dest: './uploads' }))
create(
#Body() body: CreateAssetDto,
#User() user: RequestUser,
#UploadedFiles() files: Array<Express.Multer.File>,
) {
console.log(files, body, user.userId);
//return this.assetsService.create(body, user.userId);
}
NestJs controller function that works (note the use of the field name images.0):
#Post()
#UseGuards(AuthGuard('jwt'))
#UseInterceptors(FilesInterceptor('images.0', 30, { dest: './uploads' }))
create(
#Body() body: CreateAssetDto,
#User() user: RequestUser,
#UploadedFiles() files: Array<Express.Multer.File>,
) {
console.log(files, body, user.userId);
//return this.assetsService.create(body, user.userId);
}
I'm already using RTK Query with different endpoints that return JSON which are working as expected. But there is one endpoint that returns XML. I can see in the network tab that HTTP response is correct but RTK Query's auto generated hook returns data as undefined.
Here's is my query definition:
import { myApi } from './base';
export const excel = myApi.injectEndpoints({
endpoints: (builder) => ({
fetchExcelUserList: builder.query({
query: () => ({
url: 'excel/user_list',
method: 'GET',
headers: {
'Content-Type': 'application/xml; charset:utf-8',
},
}),
}),
}),
});
export const { useFetchExcelUserListQuery } = excel;
That's how I use it:
const { data } = useFetchExcelQuery('');
console.log(data);
If this explanation isn't enough, check this link that describes the same problem.
Thanks a lot.
Your data is undefined, because your query goes into an error state - by default, everything will be parsed as json. You can provide a custom parsing function using the responseHandler functionality of fetchaseQuery though.
I'm trying to update my mongodb database in javascript by accessing some documents from the database, changing a specific document and then performing a patch request via axios.
When I get to the patch request I'm able to update the database however the promise is stuck on pending and thus, the then() part of the code is not run.
This is the main structure of the code:
In the first part the documents are requested from the database via axios.get:
function updateDocument(someinputdata){
g = axios.all([axios.get('/getData1),axios.get('/getData2)])
.then(response => {
Data1 = response[0].data;
Data2 = response[1].data;
adjustData(Data1,Data2);
});
}
In the second part a specific document is changed and a patch request is called:
function adjustData(Data1,Data2){
...getting specific document and change value from specific field...
var newRec = {
title: "dummyTitle",
rate: newRateValue
};
promise = axios({
url: '/patch/The Real Title',
method: 'PATCH',
data: newRec,
headers: { "Content-Type": "application/json" }
})
.then(() => {
console.log('I want this text to display but it doesn't')
});
}
If I console.log(promise):
Promise {<pending>}
__proto__: Promise
[[PromiseState]]: "pending"
[[PromiseResult]]: undefined
On the server side I have this:
router.patch('/patch/:title', (req,res) => {
const updatedPost = Model.updateOne(
{ "title": req.params.title},
{ $set: { "rate" : req.body.rate}},
(err, result) => {
if(err) {
console.log(err);
throw err;
}
})
.then(
console.log('This text is displayed');
)
})
I want to use the first then() part to update some HTML
Why is the patch request stuck on pending (so not fulfilled or rejected)?
I've figured out what my problem was.
I needed to add
res.json({msg: "Your data has been saved"});
to the code on the server side.
I want to get the Author field from Discussion forum list in SharePoint online using REST API in POST method. I tried the below approach, it is not working.
var queryUrl =
'?$select=ID,Title,Body,Author/Title,Folder/ItemCount,FieldValuesAsText/FileRef&$expand=Author,FieldValuesAsText,Folder/ItemCount';
var url =
siteUrl +
"/_api/Web/lists/GetByTitle('" +
listName +
"')/GetItems" +
queryUrl;
var camlQuery =
'<View><Query>' +
getQueryParams() +
"<OrderBy><FieldRef Name='DiscussionLastUpdated' Ascending='False'/></OrderBy></Query><RowLimit>12</RowLimit></View>";
var requestData = {
query: { __metadata: { type: 'SP.CamlQuery' }, ViewXml: camlQuery }
};
jQuery.ajax({
url: url,
method: 'POST',
data: JSON.stringify(requestData),
headers: {
'X-RequestDigest': $('#__REQUESTDIGEST').val(),
Accept: 'application/json; odata=verbose',
'Content-Type': 'application/json; odata=verbose'
},
success: function(data, status, jqXHR) {
dfd.resolve(data);
},
error: function(xhr) {
dfd.reject(xhr);
}
});
return dfd.promise();
The output is like below.
As I have explained in this post, $expand doesn't seem to work on some special columns (like People), when querying via POST. The best way will be to use the Items API.
However, if you only want to proceed with this approach then, try replacing the queryUrl value with the following.
var queryUrl ='?$select=ID,Title,Body,Folder/ItemCount,FieldValuesAsText/FileRef,FieldValuesAsText/Author&$expand=FieldValuesAsText,Folder/ItemCount';
Basically, what I am trying to do is that instead of directly querying the Author field, I am requesting it from under the FieldValuesAsText. Pretty much the way you have requested the FileRef property.
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;
});