I use axios, the answer to my query comes in the form of response.data.response.object. How can I get an answer without response.data immediately response.object??
You cannot achieve what you want like that, axios returns the body of the response from within the data object.
Although, you can do this:
let response = response.data.response;
And then you can use response.object
EDIT: As stated in the other answer, this is definitely doable, although I would advise against manipulating the structure in which axios sends its response as this makes assumptions about the structure of the JSON response. (especially if being setup as a global setting)
axios.defaults.transformResponse = [function (data) {
// Do whatever you want to transform the data
return JSON.parse(data).response.object;
}],
then now you can access to your object by just typing: response.data
It's work
export function name(param) {
return axios.get(`URL`,
{transformResponse: axios.defaults.transformResponse.concat((response) => {
return response.response
})
}
)}
Related
Here is my back end route, is there something obvious that im missing when it comes to the returned data? I'm more experience with array manipulation, so when dealing with objects rather than forcing it into an array after returning data, how can I restructure this to return an array?
router.get('/caseDetail/:caseName', (req,res) => {
db.caseDetail.findAll({
include : [db.Part,db.Fault,db.Disposition,db.Contact,db.Site],
where : {
caseName:{
[Op.like]: [req.params.caseName]}
}
}).then((response) => {
console.log(response);
res.json(response)
}).catch((error) => {
console.log(error);
})
})
Currently I'm returning an Object rather than an array of objects, which is what im looking for,
you forget to use return in res.json(response)
try return res.json(response)
The issue here was a syntax error on my front end route,
After changing
let items = await axios.get(`/api/caseDetail/:${caseName}`);
to
let items = await axios.get(`/api/caseDetail/${caseName}`);
Everything fell into place and my use of [Op.like] worked like a charm. Thank you all for the help!
Firstly, sorry if my english is bad, i'm not native.
My problem is simple : i already succeded at post some form data from VueJS to ExpressJS API using axios just like that:
axios.post('urlOfMyAPI', this.body).then(response => this.rep = response.data);
The "this.body" thing is an object called body and inside this object, i map all my inputs, like that by example:
<v-textarea v-model='body.text'></v-textarea>
It work well, expressJS can take the data and do the job but when i try to do it with a "v-file-input", all the data inputs go to the API correctly, except the file. When i'm trying to console.log in my API (see the screen under) a random data from input in my API, the data is rendered in my console but the data file is rendered as "undefined".
Have to say one last thing : When i do "console.log(this.body)" in vueJS before the axios post, my file is in the body like expected, so the problem is with axios. I tried to find something on internet but just got some things with a "FormData" object i don't understand and tried to use without success.
My API Code btw, just for example :
exports.Create = (req,res) => {
console.log(req.body.text);
console.log(req.body.file.name);
}
Thanks you if you help me
You have to use formData when submitting files to axios, otherwise, your files won't be available on server-side.
This is a simple method that performs an upload of a file. Please note: if you want to send additional data within your request, you have to add as many formData.append() as you have properties.
uploadAvatar () {
const formData = new FormData()
formData.append('avatar', this.file)
formData.append('other_field', this.otherField)
axios.post('/avatars/upload', formData)
.then((response) => {
console.log(response.data)
})
.catch((e) => {
console.log(e)
})
}
From my experience, if you have a huge form and you want to avoid many formData.append(), the best option is to handle your uploads separately.
My current NuxtJS Application contains the following code:
// Create a new Canvas-Object on a Whiteboard
async createCanvasObject({ state }, canvasObject) {
if (!state.id) {
console.error(' Canvas ID is not defined!');
return;
}
console.log(canvasObject);
console.log(canvasObject.mtiID);
await this.$axios
.$post(`/whiteboard/${state.id}/canvas/object`, {
object: canvasObject,
})
.then((res) => console.log(res));
},
What should this code do?
It should send a passed object canvasObject via POST-Request to my backend, without modifying it.
The canvasObject itself is a JSON-Object, which describes an Object on a Canvas.
The logging directly before the Axios-Call yields something like this:
As you can see, there is a lot of stuff defined, and espacially the attribute mtiID.
Now the Problem:
If we look at the request, we can see, that a lot of stuff got stripped away from my JSON, including the mtiID. I have no idea why. The only 'Middleware', that is currently applied to Axios just logs every request to the console, without modifying it.
I'm new to axios.
In the past when I've made http requests I'm used to getting back an array/array of objects and this allows me to easily format the data how I want by using functions such as map and reduce. I then would render it to the DOM.
I've noticed in the response I get back is an observer object. How would I go about making the request so it gives me back an array? What is the standard for dealing with this observer object?
getSomething (myId) {
return axios.get('/api/getSomething', {params: {'id': myId}})
.then(response => console.log(response.data))
.catch((promise) => this.handleError(promise));
}
Thanks
EDIT:
Updated code.
To clarify, when I call getSomething() response.data is an object even though I am sending it as an array on the backend. I am assuming that axios is changing this array to an object. The object has a bunch of extra properties like __ob__ and get 0
So I found the issue. If you pass through an array where the keys are not in order e.g. [1: [], 5: [], 6:[]]. Javascript will change it into a observer object which has different properties in order to maintain the keys. This issue is not related to axios.
You can do something as simple as the following to access the data:
axios.get('/some/url').then(response => {
console.log(response);
});
In my React/Redux app, I make a call to my backend API which returns a text response. I then use the following line to retrieve the text. The issue I'm seeing is that my code seems to put two sets of quotes around the text I receive.
So, my API returns Hello World! but in the code below it becomes ""Hello World!""
My API is really returning a string so there will always be a set of quotes around the text such as "Hello World!" which is perfectly fine. I just don't understand why I'm getting two sets of quotes.
Any idea why?
export const callApi = (request) => {
return (dispatch) => fetch('/api/getsometext', fetchOptionsPost(request))
.then((response) => {
if(!response.ok) {
// Request failed
dispatch(setBadRequest(true))
} else {
const myText = response.text() // This is where I'm getting double quotes
.then((myText) => dispatch(setMyText(myText)))
}
})
}
Simply quoting #Kaiido's hint as an answer so I does not get lost in the comments:
Your server sends the data with these quotes, probably because it
thinks it should send it as JSON. So either reconfigure your API so it
doesn't try to send it as JSON, either simply use Response.JSON() so
that your client-side parses it correctly.