VUE: Issues with fetching data when I use Pagination - vue.js

I have a a set of data which I can access for the first page. But as soon as I use the pagination and trying to press next page, then I can't access the data. I get the 401 issue.
created(){
this.fetchNotater();
},
methods: {
fetchNotater(page_url){
let vm = this;
// api/borgernotater works perfectly. But when I use the page_url then it won't accept my api_token
page_url = page_url || 'api/borgernotater';
fetch(`${page_url}?api_token=${window.Laravel.apiToken}`)
.then(res => res.json())
.then(res => {
this.notater = res.data;
vm.makePagination(res);
})
.catch(err => console.log(err))
},
makePagination(res){
let pagination = {
current_page: res.current_page,
last_page: res.last_page,
next_page_url: res.next_page_url,
prev_page_url: res.prev_page_url
};
this.pagination = pagination;
}

You have a typo in your API request URL construction: parameters need to be separated with &. You can see that when you are requesting page 2, you have two questions marks in your URL and that’s an invalid query string, and the API request URL will not be parsed correctly. It should be: ?page=2&api_key=....
With that in mind, it might be helpful to use a third party library, like query-string on NPM, to perform parsing and adding payload to your query string.

Related

How do i retrive the city name from opengatedata.com

'''if (await permission()) {
Geolocation.getCurrentPosition(
async position => {
await fetch(
`https://api.opencagedata.com/geocode/v1/json?q=${position.coords.latitude}+${position.coords.longitude}&key=apikey&pretty=1`,
).then(result => {
console.log(result.data);
});
},
error => {
console.log(error.code, error.message);
},
);
}'''
How do i retrive the returned location from the response sent to me
The things it sends me seems like gibrish and have no clue what to do and i am building the app in react-native using tsx
All you need to do is console the response to make sure that you are receiving your response as expected after that you've multiple choices to extract the required data e.g. Destructuring or looping through the response (quite expensive + time taking) or you can use the filter method, in a nutshell, there are tons of way to get your required data from the response and it's just a matter of your taste(like whichever you prefer)

GET Request fails in Vuejs Fetch but works perfectly in Postman and in browser due to 302 redirection

I have a web application built using NuxtJS/Vuejs within that I have a field where user can provide the URL and my application should make a GET request to that URL and obtain the data. Mostly the URL is related to GitHub from where it should fetch XML/JSON the data.
When I provide a certainly URL in browser/Postman then the redirection happens and data from the redirected URL is loaded. I want to achieve the same in my code but it's not happening and I get the error:
index.js:52 GET {{URL}} net::ERR_FAILED 302
But these URL works perfectly in browser and in Postman without any issue. Following is my code where I am making the request using Vuejs Fetch:
fetch(inputURL, {
method: 'GET'
})
.then((response) => {
console.log('RESPONSE')
console.log(response)
})
.catch((error) => {
console.log('ERROR')
console.log(error.response)
})
Using the Axios:
axios
.get(inputURL)
.then((response) => {
console.log("RESPONSE");
console.log(response);
})
.catch((error) => {
console.log("ERROR");
console.log(error);
})
I tried setting various header, I tried using axios etc but nothing seems to work for me. Can someone please explain to me what am I doing wrong and how to fix this issue? Any help or workaround would be really appreciated.
First of all, the 'Access-Control-Allow-Origin' header is something that should be set up on the server side, not on the client making the call. This header will come from the server to tell the browser to accept that response.
The reason why your code works from postman/browser is because you're not under the CORS rules when you request it like that.
One way around it, would be to make a call to your backend and tell the backend to call GET the data from the URL provided and then return it to your front-end.
Example:
//call_url.php
<?php
$url = $_GET['url'];
$response = file_get_contents($url);
echo $response
?>
//vue.js component
<input type="text" v-model="url"></input>
<button type="button" #click="callUrl">call me</button>
...
methods: {
callUrl() {
axios.get('call_url.php?url=' + encodeURIComponent(this.url))
.then(response => {
//...do something
}
}
}
As mentioned in another answer it's not possible for any library including Fetch and Axios to make requests and obtain the Data due to various security policies. Hence, I created a method in my Spring boot application that will obtain the data from URL and I make a request to my Spring boot using Axios.
import axios from 'axios'
axios.post('/urlDataReader', inputURL)
.then((response) => {
console.log(response)
})
.catch((error) => {
console.log(error)
})
Spring boot app:
//Method to read the data from user-provided URL
#PostMapping(value = "/urlDataReader", produces = "text/plain")
public String urlDataReader(#RequestBody String inputURL) {
final String result = new RestTemplate().getForObject(inputURL, String.class);
return result;
}

How to retrieve cookies in express via browser?

I've been trying to figure this out for 2 days now, but to no avail. I'm using cookie-parser and have followed the code of other people but it's still not working. It works perfectly in postman, but not on the browser. The browser I'm currently using is google chrome, but I've also tested it on microsoft edge which gives the same result.
app.get('/testCookie',(req,res) => {
res.cookie('username','flavio');
res.json({message:req.cookies});
})
// frontend
const data = await axios.get('http://localhost:5000/testCookie');
console.log(data); // returns {}
Asper, I understand you want to set cookies and access it in the client-side, then this might help you.
Server-side
const cookieConfig = {
httpOnly: false,
maxAge: 315569260000,//age of cookie any value possible
}
app.get('/testCookie',(req,res) => {
res.cookie('username','flavio',cookieConfig);
})
Client side
let data = document.cookie
.split('; ')
.find(row => row.startsWith('username'))
.split('=')[1];
console.log(data)

Using fetch() with API

I try to use fetch() to get the data from https://swapi.co/
With this code I get undefined but in the "Network" section in chrome I see the data I need. How I can access it?
fetch('https://swapi.co/api/people/1/')
.then(resp => resp.json)
.then(obj => console.log(obj));
Hello this will fetch the data returning it as json
fetch('https://swapi.co/api/people/1')
.then(function(response) {
return response.json();
})
.then(function(myJson) {
console.log(JSON.stringify(myJson));
});
If you have right environment for calling to the fetch API there maybe 2 result
You will get the right result data
You will get an error
fetch(url) // Call the fetch function passing the url of the API as a parameter
.then(function() {
// Your code for handling the data you get from the API
})
.catch (function() {
// This is where you run code if the server returns any errors
});
Use a catch for seen what is going wrong with your request

Call API with Another Api response data in Nuxtjs

Im making a website with Nuxtjs, i want when i open any page of the website to get user information from the server using Axios, and i want to use these information to call another API's from the website.
For example: i will get the User id and Client id from the server and use them on the API URL, lets say i got User id = 5, Client id = 10
i will call another API's and use these informations
http://****/getItems?userid=5&clientid=10
Now my problem is the second API call before the first API finished so i didn't got the user informations yet.
Could you please help me with this issue, note that i want to get the user information on all pages. so if i reload the page in any page i want to get user informations.
So i call the user information API from a Layout and call the other API's from another components.
Thanks.
First you should use Axios module officially provided by Nuxt.js here, https://github.com/nuxt-community/axios-module. They have make the integration between Axios and Nuxt.js easier.
Axios uses promise so you can easily chaining method to do it. Let say you wanna get information from /get/product with data gotten from the url you mention before http://****/getItems?userid=5&clientid=10, you can easily do that like this
this.$axios.$get('/getItems?userid=5&clientid=10')
.then(data => {
// You can use your data received from first request here.
return this.$axios.$post('/get/product', {
id: data.id,
clientId: data.clientId
})
})
.then(data => {
// You can use your data received from second request here.
console.log(data)
})
Explanation
This part,
this.$axios.$get('/getItems?userid=5&clientid=10')
the axios will get the data from the url provided, when the data is received, we can use it within then() block as it accept callback as a parameter.
.then(data => {
// You can use your data received from first url here.
...
})
After that, if you wanna use your data you can easily return the axios request again with proper parameter you wanna send.
return this.$axios.$post('/get/product', {
id: data.id,
clientId: data.clientId
})
And again you can use the data received from second axios request within then() block.
.then(data => {
// You can use your data received from second request here.
console.log(data)
})
Updated
Oke, based on the clarification on the comment section below. We can return the axios promise in first action and then on the second method we can dispatch the first action,
actions: {
callFirst ({ commit }) {
return this.$axios.$get('/get/first')
.then(firstResult => {
commit('SET_FIRST', firstResult)
return firstResult
})
},
callSecond ({ dispatch, commit }) {
return dispatch('callFirst').then(firstResult => {
return this.$axios.$post(`/get/${firstResult.userId}`)
.then(secondResult => {
commit('SET_SECOND', secondResult)
return secondResult
})
})
}
}
Using that way, you just need to put the callSecond() action whereever you want get the second data. And you also don't need to put the callFirst() action on default.vue.