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

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

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.

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

express api responds to GET and POST but not PUT and DELETE through cors but responds properly when the request is local

When I'm sending a request to my express API through Axios, the GET and POST request respond correctly, but PUT and DELETE does not.
This is not a code problem as all my tests are passing, I believe this is related to CORS
I have installed morgan npm package to log the requests to the server.
The GET and POST are working fine, but PUT/DELETE are not and console.log() messages in those route handlers don't even show up!!!
The response from PUT and DELETE is 404
app.js
app.use(cors())
router.js
router.delete('/', (req, res) => {
// this log statement does not show up!
console.log('request recieved')
Controller.DeleteItem(req.body.data.title).then(() => {
res.redirect('/')
}
}
console output
OPTIONS 204
DELETE 404
request
axios.delete('http://localhost:5000/', {
data: {
title: title
}
}
This was discussed outside SO : the issue was that the put and delete routes were placed inside the post route, the indentation (not appearing here) was obvious when seeing the whole code in context.

How to use DIBS payment system with vuejs?

I have the following sample code, in a nuxtjs/vuejs project
<template>
<v-app>
<div id="dibs-complete-checkout"></div>
</v-app>
</template>
<script>
export default {
head () {
return {
script: [
{ src: 'https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js' },
{ src: 'https://test.checkout.dibspayment.eu/v1/checkout.js?v=1' }
]
}
},
created () {
this.$axios.get('test/11').then((response) => {
var checkoutOptions = {
checkoutKey: response.data.checkOutKey,
paymentId: response.data.dibsPaymentId,
containerId: 'dibs-complete-checkout',
language: 'en-GB'
}
var checkout = new Dibs.Checkout(checkoutOptions)
checkout.on('payment-completed', function (response) {
})
checkout.on('pay-initialized', function (response) {
checkout.send('payment-order-finalized', true)
})
})
.catch((e) => {
console.error(e)
})
}
}
</script>
What is happening in there, is:
An external script from dibspayment.com is loaded
There is an axios call to the backend to return a checkoutKey and a paymentId, necessary in the checkoutOptions object
The script loaded from dibspayment.com contains an object, Dibs, which has a method called Checkout(checkoutOptions)
The development server is running on http.
I get several errors. One is "Dibs is not defined"
./pages/index.vueModule Error (from ./node_modules/eslint-loader/index.js):C:\git\ssfta_web\pages\index.vue 29:28 error 'Dibs' is not defined no-undefâś– 1 problem (1 error, 0 warnings)
Which is odd, because the page loads and is rendered inside the
Another error is
OPTIONS https://test.checkout.dibspayment.eu/api/v1/theming/checkout 401 (Unauthorized)
And the last error is
Access to XMLHttpRequest at 'https://test.checkout.dibspayment.eu/api/v1/theming/checkout' from origin 'http://10.0.75.1:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
I've tried:
Contacting DIBS payment support team, where responses are both slow and offer no real advice (providing me with a link to the top level FAQ page). I suspect that they use their sales department to answer inquiries.
running it on https, that made it worse
running it behind a nginx reverse proxy, which has an ssl certificate, the process running the code itself over http but nginx 'converts' (?) it to https
numerous hail maries that made everything worse
An image of the current situation
I don't really have a question, I just hope/suspect that I'm forgetting some basic configuration or detail that someone could spot
Any advice appreciated.
Had this issue this week.
Contacted Dibs Support with the issue, left work and the next day i returned to an email from support with a copy of my API-keys which i already had received, but after testing out my project again (Which had no changes) this error magically disappeared, so apparently this issue was something on their end. Assuming my keys were missing the proper authorisations.
Read the error message properly, it is an es lint error
Did this to solve it
/*eslint-disable */
var checkout = new Dibs.Checkout(this.checkoutData)
/* eslint-enable */

youtube-data-api with vue js and axios

I am a beginner developer and just learned basic javascript 4 months ago, and vue over the last 4 days. I have never worked with google api before. What I am trying to do by using the vue documentation is display a youtube playlist based on music genre. I keep getting:
Access to XMLHttpRequest at 'data:text;charset=utf-8,' (redirected
from 'https://googleads.g.doubleclick.net/pagead/id') from origin
'null' has been blocked by CORS policy: No
'Access-Control-Allow-Origin' header is present on the requested
resource.
followed by:
[Violation] Added non-passive event listener to a scroll-blocking
'touchstart' event. Consider marking event handler as 'passive' to
make the page more responsive.
Google support told me to post on stackoverflow to get a google engineer to help. Here is the get request i'm using and I removed the playlistID and apikey from the url
created(){
this.getPlaylist();
},
methods: {
getPlaylist: function () {
axios.get('https://www.googleapis.com/youtube/v3/playlists?part=snippet&id=PLfY-m4YMsF-OM1zG80pMguej_Ufm8t0VC&key=AIzaSyCnGeoYhG3HXL6j8bIH-mwgwCHYyqdBW4s', function(response){
this.playlist = response.items
console.log(response)
})
.catch( function(error){
console.log('Error: ', error)
})}}