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

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;
}

Related

how solve 404 error in axios post request in vue?

i want send request to an api but i have 404 erro and i have nothing in network
can you help me?
my code:
loginMethod() {
const config = {
userName: "test#gmail.com",
password: "1234test",
};
return new Promise((resolve) => {
ApiService.post("api/authentication/login", config)
.then(({ data }) => {
console.log(data);
resolve(data);
})
.catch(({ response }) => {
console.log(response);
});
});
},
and ApiService function:
post(resource, params) {
console.log(params);
const headers = {
"E-Access-Key": "bb08ce8",
};
return Vue.axios.post(`${resource}`, params, { headers: headers });
},
Based only on what I can see in your code, you are not telling axios the complete URL if I'm right about it, and you didn't declare it somewhere else do this:
axios.post('yourdomain.com/api/authentication/login',params)
or
axios({
url:'yourdomain.com/api/authentication/login',
method:post,
data:{}
})
or
in your main js file or any other file that you import axios (if you are sharing an instance of it globali):
axios({baseurl:'yourdomain.com'})
and then you don't need to write the complete url everywhere and just insert the part you need like you are doing now and axios will join that address with the baseurl,I hope it helps
I guess the URL "api/authentication/login" might be wrong and the correct one would be "/api/authentication/login" that starts with /.
404 error means the resource referred by the URL does not exist. It happens when the server has deleted the resource, or you requested a wrong URL accidentally, or any wrong ways (e.g. GET vs POST)
To make sure if you were requesting to the correct URL (and to find where you're requesting actually), open Google Chrome DevTools > Network panel. You might need reload.
The url api/xxx is relatively solved from the URL currently you are at. If you were at the page http://example.com/foo/bar, the requested URL becomes http://example.com/foo/bar/api/xxx. Starting with / means root so http://example.com/api/xxx.
This answer might help to understand the URL system: https://stackoverflow.com/a/21828923/3990900
"404" means your API Endpoint is not found. You need to declare the location of your API Endpoint exactly. For example: http://localhost:8080/api/authentication/login.

Nuxtjs/Vuejs with axios trying to access URL results in Access to XMLHttpRequest at has been blocked by CORS policy

I am aware there are many answers related to this question but since nothing seems to work I am posting here.
I have NuxtJS/Vuejs application within which users can provide the GitHub URL (mostly the URL will contain the XML/JSON files). After getting the URL, I want to make a request to the URL using the axios and obtain the data present within the URL.
When I try to make a request i get the following error:
Access to XMLHttpRequest at 'GitHub URL' from origin 'http://localhost:3000' has been blocked by CORS policy: The 'Access-Control-Allow-Origin' header contains multiple values 'Some GITHUB URL', but only one is allowed.
When I provide the same URL in the browser then I get the 302 status and obtain the raw JSON/XML data after redirection. I want to implement the same in my code.
If data is not found in the URL then obtain the redirection URL from the response and make another request with the new URL. But due to the CORS error and other error GET GIT HUB URL net::ERR_FAILED I am unable to get the response.
I tried many things mentioned on the website such as:
Adding proxy as mentioned here: https://stackoverflow.com/a/55481649/7584240
Adding a prefix to URL as mentioned here: https://stackoverflow.com/a/56781665/7584240
Adding the condition to axios as mentioned here: https://stackoverflow.com/a/48293817/7584240
And many other things but nothing seems to work for me and getting the same error. Can someone please help me with this issue?
Following is the sample code I have (The code is part of VUEX Store actions):
export const actions = {
obtainURLData ({ commit, state, dispatch, rootState }, inputURL) {
axios
.get(inputURL)
.then((response) => {
console.log('INSIDE RESPONSE')
console.log(response)
console.log(response.data)
if (response.status === 200) {
}
})
.catch((error) => {
console.log('INSIDE ERROR')
console.log(error)
console.log(error.response)
console.log(error.response.data.detail)
console.log(error.response.status)
})
}
}

Axios POST request not working when passed object

I am trying to do a post request in a vue js app using axios to a local API and the response is returning empty data. The post request on API is working fine using Postman tool. Below is my code
var the_data = {
title: 'This is title',
description: 'this is description'
}
axios.post('/api/snippets/insert', the_data)
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
On the API end, I am using a simple PHP script and printing whole $_POST request data using this code
var_dump($_POST);
But this is returning empty array.
I was running into this as well. Axios does not send the POST data in the form you're expecting. You need something like http://github.com/ljharb/qs and then use axios.post('/api/snippets/insert', Qs.stringify(the_data)). Please note this build on cdnjs uses Qs, not qs.
Alternatives to qs would be e.g. JSON.stringify() or jQuery's $.param().

React-native Fetch GET, while passing request items to the url

I have a Django-REST API that I am trying to access with a React-native app. I would like to achieve the same result that the command line
http GET http://mywebsite.com/api param1=value1 param2=value2
but using the fetch() function from the networking tutorial. How can I specify the request items to the fetch while using the GET method?
EDIT: my goal is to able to perform a token authentication to a django rest API which need these request item for the page to be accessed.
fetch() uses the exact URL string you provide to perform the request.
Include URL params in your url like when you are calling fetch()
fetch("http://whatever.xyz?param1=1&param2=2")
The simplest way to handle this is by using something similar to the following function
function apiCall() {
return fetch('http://mywebsite.com/api/?param1=value1&param2=value2')
.then((response) => response.json())
.then((responseJson) => {
return responseJson.movies;
})
.catch((error) => {
console.error(error);
});
}

Stripe API request using VueJs

I am making the following get request using vuejs:
this.$http.get(`api.stripe.com/v1/search?query="+email"` ).then((response) => {
console.log(response)
})
the problem is that this request is pointing to:
http://localhost:8000/api/api.stripe.com/v1/search?query=%22+email%22
And I need to point to:
https://api.stripe.com/v1/search?query=%22+email%22
How can I achieve this?