How to get response and show from backend in vue js - vue.js

I have the following code:
data: function () {
return {
searchResults: []
}
methods: {
show() {
return axios({
method: 'get',
url: this.url,
headers: {
'Authorization': `Bearer ${localStorage.getItem('user-token')}`
}
})
.then (function (response){
return response.data['searchResults'];
})
.catch(e => { console.log(e) })
},
}
I have an onClick button. When I click the button, the show function executed and it send get response to my spring boot. After that it retrieves some data as I see in console, but the data is not displayed in browser. How can I fix it? The data I get looks like this:
JSON:
0: Object { "Code": "4326", code_color: 2, "name": "SomeName", … }
1: Object { "Code": "4326", code_color: 2, "name": "SomeName", … }
2: Object { "Code": "4326", code_color: 2, "name": "SomeName", … }

You should assign the returned data from api call in the show method to searchResults in the components data, so instead of
return response.data['searchResult']
you can use
this.searchResults = response.data.searchResult

Related

How to migrate using request library for a POST request to Axios?

I've been grinding this out for awhile but am definitely hard blocked. I want to migrate my program from a deprecated request library to a different one. I chose axios but can't get it to work. All I need to be able to do is make the post request in a similar way that lets me access the response body.
Here is my working deprecated library request code:
const getPage = (apiUrl, size, stagedDateAfter) => {
let options = {
json: true,
body: {
"summary": false,
"sort": [{"stagedDate": "asc"}],
"search_after": [stagedDateAfter],
"queries": [],
"page": {"max": size}
}
};
request.post(apiUrl, options, (error, res, body) => {
if (error) {
return console.log(error)
}
if (!error && res.statusCode === 200 && keepGoing == true) {
if(body.meta.total == 0 || (!body)){
throw("error");
}
/*
Code works from this point, can access body, data, etc
*/
}
}
My failing axios library code:
function checkResponseStatus(res) {
if(res.statusCode === 200 && keepGoing == true) {
return res
} else {
throw new Error(`The HTTP status of the reponse: ${res.status} (${res.statusText})`);
}
}
const headers = {
'Content-Type': 'application/json'
}
const getPage = (apiUrl, size, stagedDateAfter) => {
let options = {
json: true,
body: {
"summary": false,
"sort": [{"stagedDate": "asc"}],
"search_after": [stagedDateAfter],
"queries": [],
"page": {"max": size}
}
};
axios.post(apiUrl, options, headers)
.then(response => {
console.log(response);
if(!response){
checkResponseStatus(response);
}
return response;
})
.catch(error => {
console.log(error.res)
})
.then(data => { //This code doesn't work since response not defined here
if(response.data.status == 200){
console.log(data);
}
});
All I need is to be able to access the response body using axios similarly to how I did with the request library but I'm reading the documentation, api, etc and I just cant seem to get the exact format right.
Solved it! Correct format that lets me access body properly.
let options = {
url: stringURL,
method: 'POST',
json: true,
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
data: {
"summary": false,
"sort": [{"stagedDate": "asc"}],
"search_after": [stagedDateAfter],
"queries": [],
"page": {"max": size}
}
};
axios(options)
.then((response)=>{
//rest of code

vue js axios, send a POST to elasticsearch

In Vue JS using Axios I'd like to make a POST request to an Elasticsearch instance. More precisely I'd like to store a search template (https://www.elastic.co/guide/en/elasticsearch/reference/current/search-template.html#pre-registered-templates)
POST _scripts/<templateid> {
"script": {
"lang": "mustache",
"source": {
"query": {
"match": {
"title": "{{query_string}}"
}
}
}
} }
It works with CURL but I'm getting an error 400 when I'm trying with Axios.
My code is the following (with test as templateid)
var dataBody = {
"script": {
"lang": "mustache",
"source": {
"query": {
"match": {
"keyword": {
"query": "{{search_term}}"
}
}
}
}
}
};
this.$http.post(
"https://es-url/_scripts/test",
{
contentType: "application/json; charset=utf-8",
crossDomain: true,
dataType: "json",
headers: {
Authorization: "Basic " + btoa("elastic:password")
},
params: {
source: dataBody,
source_content_type: 'application/json'
}
}
)
.then(response => {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
Error:
Error: Request failed with status code 400
at createError (createError.js?2d83:16)
at settle (settle.js?467f:17)
at XMLHttpRequest.handleLoad (xhr.js?b50d:61)
I'm using the same Axios parameters to retrieve data (from my search queries), it works just fine, the difference is I can use GET for my search queries while I need to use POST to store a search template.
Looks like you've got Axios and jQuery's $.ajax mixed up.
If you are actually using Axios, it would look like this
this.$http.post('https://es-url/_scripts/test', dataBody, {
auth: {
username: 'elastic',
password: 'password'
}
})
Note that for this to work, you would need Elasticsearch configured with http.cors.enabled=true. See https://www.elastic.co/guide/en/elasticsearch/reference/current/modules-http.html

How do I format an array passed to params of an axios get to this specific format: [0].mfr=mfr0&[0].mpn=mpn0&[1].mfr=mfr1&[1].mpn=mpn1

I'm making a axios get call to a web api that is looking to have the query string parameters in this specific format which seems uncommon: [0].mfr=mfr0&[0].mpn=mpn0&[1].mfr=mfr1&[1].mpn=mpn1
I've been trying to use the Qs library to stringify the params in the paramsSerializer option.
parts = [{ mfr: "mfr0", mpn: "mpn0" }, { mfr: "mfr1", mpn: "mpn1" }]
findParts(parts, token) {
return axios
.request({
url: "https://<serveraddress>/api/v1/parts/findparts",
method: "get",
params: parts,
headers: {
Authorization: "Bearer " + token,
"Content-Type": "text/plain"
}
})
.catch(error => {
console.log(error);
Vue.notify({
type: "error",
title: "Unable to find parts",
text: "Unable to find parts"
});
});
}
result
0={"mfr":"mfr0","mpn":"mpn0"}&1={"mfr":"mfr1","mpn":"mp1"}
paramsSerializer: function(params) {
return qs.stringify(params);
},
or
paramsSerializer: function(params) {
return qs.stringify(params, { arrayFormat: "brackets" });
},
or
paramsSerializer: function(params) {
return qs.stringify(params, { arrayFormat: "indices" });
},
result
0[mfr]=mfr0&0[mpn]=mpn0[mfr]=mfr1&1[mpn]=mpn1
paramsSerializer: function(params) {
return qs.stringify(params, { allowDots: true });
},
result
0.mfr=mf0&0.mpn=mpn0&1.mfr=mfr1&1.mpn=mpn1
I can create a custom paramsSerializer but I was wonder if there a way to manipulate qs or the passed parts array to get the correct query string results without having to manually create the query string and url encode the values?

React-admin: Missing headers object in data provider

I am trying to create a custom data provider for my API. I am able to login and GET_LIST but unable to process the received data. I have adapted the required output format for the API responses and also included the Content-Range header.
With Postman all headers are returned but they seems to be missing in the "response" I am receiving in the convertHTTPResponse method.
Since headers are emtpy, the list won't appear and showing the error:
Warning: Missing translation for key: "Cannot read property 'hasOwnProperty' of undefined"
Certainly something obvious for experimented devs, please help!
Edit: Fixed it by saving the headers before converting the res.json()
myDataProvider.js
export default (apiUrl, httpClient = fetchUtils.fetchJson) => {
let url = '';
const token = localStorage.getItem('token');
const options = {
headers: new Headers({
Accept: 'application/json',
Authorization: 'Bearer ' + token
}),
};
switch (type) {
case GET_LIST:
{
const {
page,
perPage
} = params.pagination;
const {
field,
order
} = params.sort;
const query = {
sort: JSON.stringify([field, order]),
range: JSON.stringify([
(page - 1) * perPage,
page * perPage - 1,
]),
filter: JSON.stringify(params.filter),
};
url = `${apiUrl}/${resource}?${stringify(query)}`;
break;
}
default:
throw new Error(`Unsupported Data Provider request type ${type}`);
}
let headers;
return fetch(url, options)
.then(res => {
headers = res.headers;
return res.json();
})
.then(response => {
//console.log(headers);
switch (type) {
case GET_LIST:
return {
data: response.data.map(resource => ({ ...resource, id: resource.uuid })),
total: parseInt(headers.get('content-range').split('/').pop(), 10)
};
default:
return {
data: response
};
}
});
};
API call URL:
http://localhost:9000/users?filter={}&range=[0,9]&sort=['uuid','DESC']
Result with Postman:
{
"data": [
{
"uuid": "ff1xxa-ddsa-4232-b453-ed44e4dfc11d",
"email": "fr2r32442231y#domain.net",
"created_at": "2019-03-27T23:11:48.000Z",
"updated_at": "2019-03-27T23:11:48.000Z",
}
"total": 74,
"limit": 9,
"offset": 0,
"order": "DESC",
"sort": "uuid",
"success": true
}
Request Headers with Postman:
Authorization:"Bearer token123"
cache-control:"no-cache"
Postman-Token:"5e0442c7-698d-46e2-8656-50f4b10de970"
User-Agent:"PostmanRuntime/7.6.1"
Accept:"*/*"
Host:"localhost:9000"
cookie:"connect.sid=s%3AmfwRL0cVcIcBhqqGy1w6epkxjEh0nRzr.cP03XewB3Na%2B6esVOvN%2FBE5gL8gQvO%2BbWCIkC5Vbq44"
accept-encoding:"gzip, deflate"
Response Headers with Postman:
Access-Control-Allow-Origin:"*"
Access-Control-Expose-Headers:"Content-Range,X-Content-Range"
X-DNS-Prefetch-Control:"off"
X-Frame-Options:"SAMEORIGIN"
Strict-Transport-Security:"max-age=15552000; includeSubDomains"
X-Download-Options:"noopen"
X-Content-Type-Options:"nosniff"
X-XSS-Protection:"1; mode=block"
Content-Range:"users 0-9/74"
Content-Type:"application/json; charset=utf-8"
Content-Length:"13063"
ETag:"W/"3307-8yJ9evfC/wq64GCJcSnFIwWEGC8""
Date:"Thu, 11 Apr 2019 14:03:13 GMT"
Connection:"keep-alive"

Parameter pass from one api to another in react-native

I want to pass a parameter value from one API-Request to 2nd API-request so that 2nd api display result accordingly: Here is my function componentWillMount:
componentWillMount() {
axios.post('https://APISITE/api/Auth/AuthorizeByApplication?applicationId=b72fc47a-ef82-4cb3-8179-2113f09c50ff&applicationSecret=e727f554-7d27-4fd2-bcaf-dad3e0079821&token=cd431b31abd667bbb1e947be42077e9d')
.then((response) => { console.log(response.data); });
axios.get('https://APISITE//api/Stock/GetStockItems',
{
params: {
keyWord: 454534534543,
locationId: '',
entriesPerPage: 100000,
pageNumber: 1,
excludeComposites: true,
//add other params
},
headers:
{ Authorization: 'asdfasdsfdfdfdfsfsdxxx'
}
//}).then((response) => { console.log(response.data); });
}).then((response) => this.setState({ products: response.data }));
axios.get('https://APISITE//api/Stock/GetStockLevel', {
params: {
stockItemId: '2f80b45c-85ff-449b-9ad6-ffcc4bb640dd',
},
headers:
{ Authorization: 'asdfasdsfdfdfdfsfsdxxx'
}
// }).then(response => console.log(response));
}).then((response) => this.setState({ racks: response.data }));
}
Value in stockItemId is passed as static value and result displayed in console correctly. How can get stockItemId's value dynamically from 1st-api request?
Edit: Below is data result screenShots of passing stockItemId directly in api and getting from 1st api.
Getting from 1st api: stockItemId: stockItems.data.StockItemId : http://prntscr.com/i7k0j7
Directly passing value of stockItemId screenshot- stockItemId: '2f80b45c-85ff-449b-9ad6-ffcc4bb640dd' http://prntscr.com/i7jyq7
You need to handle the response data from within the then functions.
Notice the way the response from each request is passed into the following then where it can easily used.
componentWillMount() {
axios
.post('https://APISITE/api/Auth/AuthorizeByApplication?applicationId='app id'&applicationSecret='app secret'&token='app token'')
.then((authData) => {
console.log(authData.data);
return axios.get('https://APISITE//api/Stock/GetStockItems', {
params: {
keyWord: 5055967419551,
locationId: '',
entriesPerPage: 100000,
pageNumber: 1,
excludeComposites: true,
},
headers: {
Authorization: '0f32ae0d-c4e0-4aca-8367-0af88213d668'
}
})
})
.then((stockItems) => {
this.setState({ products: stockItems.data })
return axios.get('https://APISITE//api/Stock/GetStockLevel', {
params: {
stockItemId: stockItems.data.stockItemId,
},
headers: {
Authorization: '0f32ae0d-c4e0-4aca-8367-0af88213d668'
}
})
})
.then((stockLevel) =>
this.setState({ racks: stockLevel.data })
)
}
(This code is untested!)
First thing never use componentWillMount component life cycle method to set the component state or call any api request for these purpose use componentDidMount for more reading which life cycle use for which purpose read this article and Secondly just add the second api request inside the first api request response with different name response name as given below:
componentDidMount() {
axios.post('https://APISITE/api/Auth/AuthorizeByApplication?
applicationId='app id'&applicationSecret='app secret'&token='app token'')
.then((responseFirst) => {
axios.get('https://APISITE//api/Stock/GetStockItems', {
params: {
keyWord: 5055967419551,
locationId: '',
entriesPerPage: 100000,
pageNumber: 1,
excludeComposites: true,
},
headers: {
Authorization: '0f32ae0d-c4e0-4aca-8367-0af88213d668'
}
}).then((responseSecond) => this.setState({ products: responseSecond.data }));
axios.get('https://APISITE//api/Stock/GetStockLevel', {
params: {
stockItemId: responseFirst.data.stockItemId,
},
headers: {
Authorization: '0f32ae0d-c4e0-4aca-8367-0af88213d668'
}
}).then((responseThird) => this.setState({ racks: responseThird.data }));
});
}
if you are using redux then read redux documentation to handle async type actions and how to handle it.