CORS blocking client request in Nuxt.js - vuejs2

I am having issues when making a client request.
I have followed the documentation on Nuxt.js and Axios but I still can't seem to get it working. Maybe I am missing something..
My Vue component calling the vuex action:
methods: {
open() {
this.$store.dispatch('events/getEventAlbum');
}
}
The action in vuex:
export const actions = {
async getEventAlbum(store) {
console.log('album action');
const response = await Axios.get(url + '/photos?&sign=' + isSigned + '&photo-host=' + photoHost);
store.commit('storeEventAlbum', response.data.results);
}
};
And my nuxt.js.config
modules: [
'#nuxtjs/axios',
'#nuxtjs/proxy'
],
axios: {
proxy: true
},
proxy: {
'/api/': {
target: 'https://api.example.com/',
pathRewrite: { '^/api/': '' }
}
}
Anybody who can help?

I believe the issue that #andrew1325 is trying to point out is that the API provider needs to have the CORS enabled, not just your server, without changing the headers in your proxy, you're passing the same headers, which at the moment prevent access.
It seems to me that you're only missing changeOrigin
please try the following config:
modules: [
'#nuxtjs/axios',
'#nuxtjs/proxy'
],
axios: {
proxy: true
},
proxy: {
'/api/': { target: 'https://api.example.com/', pathRewrite: {'^/api/': ''}, changeOrigin: true }
}
also make sure that your front-end API url is pointing to your proxied request /api

Related

Heroku Deploy Vite Static App Won't Connect to API with Axios Using a Proxy

I think this problem follows this one on netlify API from proxy not working after deploying on netlify
I am setting up a Vite app and making an axios api request in my app component
getSuggestionList(street, zip, city) {
this.axios.get('/1.0/address/find?country=at&zip=' + zip + '&city=' + city + '&street-address=' + street + '&street-number=&offset=1&limit=100', {
auth: {
username: '7166-631A-5394-4C03-9106-0A93-C433-2613',
password: ''
}
})
Now, for development I configured a proxy in server
in vite.config.js
import { fileURLToPath, URL } from "url";
import { defineConfig } from "vite";
import vue from "#vitejs/plugin-vue";
// https://vitejs.dev/config/
export default defineConfig({
plugins: [vue()],
resolve: {
alias: {
"#": fileURLToPath(new URL("./src", import.meta.url)),
},
},
server: {
proxy: {
'/1.0/address': 'http://api.opendata.host/'
}
},
proxy: {
'/1.0/address': {
target: 'http://api.opendata.host/',
changeOrigin: true,
secure: false,
ws: true,
}
}
});
Following this guide
https://rubenr.dev/en/cors-vite-vue/
I understand this does not transfer to production, so I also tried the proxy part. I don't get a response, just like described in the netlify guide.
From Heroku docs
https://github.com/heroku/heroku-buildpack-static
I have the basic setup without proxies (leading to the initial, no-response behavior)
in static.json:
{
"root": "./dist",
"clean_urls": true,
"routes": {
"/**": "index.html"
},
"proxies": {
"/1.0/address": {
"origin": "http://api.opendata.host/"
}
}
}
And when I add proxies I get a 404 not found. When I change up the spelling: no response again, so it seems to be making a connection with the proxies configuration. But why not they way it works locally? Does anyone see my error here or having something for me to try?
I found it: for anyone else having trouble with this kind of deployment on Heroku -- the mountpoint "/1.0/address" in static.json seems to be replaced resulting in the 404 not found.
For production I added a prefix /api in my axios call, something like
var apiPath = '/1.0/address/find?country=at&zip=' + zip + '&city=' + city + '&street-address=' + street + '&street-number=&offset=1&limit=100'
var prodMountpoint = '/api' // /api/
if (import.meta.env.PROD) {
apiPath = prodMountpoint + apiPath
}
This results in a correct api call: "/api" is replaced with the proxied host, if I understand correctly. For development, the vite.config.js does its work as before.

Can't use proxy in Vue js

I'm a bit noob to network stuff, i'm not using vite (what ever was that), i've just created a simple proxy server in order to proxy to my vue site, i've searched tons of pages and didn't get the solution and yes when u guys see the error it will look simple, trust me i've checked the old endpoint URL znd it matches the resulting URL of the proxy, they point to the same place
this is the code to fetch the server:
async fetchtasks() {
const res = await fetch("api/tasks");
const data=res.json()
return data;
},
code in vue.config.js:
module.exports = {
devServer: {
proxy: {
'^/api': {
target: 'http://localhost:5000',
changeOrigin: true,
pathRewrite: { '^/api': '/api' },
logLevel: 'debug',
ws: true,
},
},
}
};
when i use 'http://localhost:5000' it works well but after i replace it with api it returns the "unexpected token < in json error", i know it's an html page, how do i get rid of it? the code is right, and i've tried different tweaks... nothing worked
module.exports = {
devServer: {
proxy: {
'^/api': {
target: process.env.VUE_APP_BASE_URL_API,
pathRewrite: { '^/api': '' }
}
}
}
}

Vue.js app getting 404 error when requesting data from the backend using proxy

all,
I am writing a front-end of my app, using Vue. I need to request some information from the back-end, launched on the same server.
I added proxy like this:
module.exports = {
devServer: {
port: 2611,
proxy: {
'/api/markets/light': {
target: 'http://localhost:2610/markets/light',
ws: true,
logLevel: 'debug',
pathRewrite: {
'^/api/markets/light': '/markets/light',
},
},
},
},
}
(I've tried different combinations of the parameters, like excluding pathRewrite, '^/api/...' instead of '/api/...', etc.)
This is how data is requested from the code:
created() {
axios.get(this.$store.getters.marketsLightLink)
.then(response => this.markets = response.data)
.catch(error => console.log(error));
}
marketsLightLink simply concatenates strings:
const store = new Vuex.Store({
state: {
marketDataHost: '/api',
markets: {
markets: '/markets',
marketLight: '/markets/light',
},
},
getters: {
marketsLightLink(state) {
return state.marketDataHost + state.markets.marketLight;
},
},
});
So when i open the page, where i should see the results of the request, i just see 404 error in the browser's console and no data downloaded. At the same time I see, that the link is proxied correctly:
[HPM] Rewriting path from "/api/markets/light" to "/markets/light"
[HPM] GET /api/markets/light ~> http://localhost:2610/markets/light
And when i press the resulting link, the requested information is shown in the browser.
Can anyone help me, what am I doing wrong please?

CORS axios Nuxt.js

I'm using an API with my Nuxt, here is my nuxt.config.js to allow the requests :
axios: {
prefix: '/api/',
proxy: true,
},
proxy: {
'/api/': {
target: process.env.API_URL || 'http://localhost:1337',
pathRewrite: {
'^/api/': '/',
}
},
}
On a specific page of my app, I need to send requests to another API from another domain. I'm using axios direclty in this Vue component :
axios.post('mysite.com/widget.rest')
As response, I obtain CORS error. Can I allow multiple API in my config ?
If you mean being able to access APIs under different URLs, AFAIK it's not possible out of the box. We tried adding proxy to different targets, but it only worked on client side, not during SSR.
What we ended up doing is having the default axios instance for our main API, and creating a plugin that creates extra axios instances for our other APIs for SSR.
Add extra "suburl" to proxy - this sorts out client side and means no CORS issues.
proxy: {
'/forum/': {
target: 'https://other.domain.com/',
pathRewrite: {'^/forum/': '/'}
},
'/api/': ...
},
For SSR to work, axios should hit directly the other API
import Vue from 'vue'
var axios = require('axios');
const forumAxios = axios.create(process.client ? {
baseURL: "/"
} : {
baseURL: 'https://other.domain.com/'
});
// this helps Webstorm with autocompletion, otherwise should not be needed
Vue.prototype.$forumAxios = forumAxios;
export default function (context, inject) {
if (process.server) {
forumAxios.interceptors.request.use(function (config) {
config.url = config.url.replace("/forum/", "");
return config;
}, function (error) {
return Promise.reject(error);
});
}
inject('forumAxios', forumAxios);
In components, you can then use something like:
async asyncData({app}) {
let x = await app.$forumAxios.get("/forum/blah.json");
You can use process.env prop of course instead of hardcoded URL.
This will hit https://other.domain.com/blah.json.

Vue-router history mode is not working when using axios

I want to get the data from http://localhost:5438/api/change?id=123 when visiting http://localhost:8080/change/detail/123, but it's not working when using history mode.
The dev config
assetsPublicPath: '/',
proxyTable: {
'/api': {
target: 'http://127.0.0.1:5438/api/',
changeOrigin: true,
pathRewrite: {
'^/api': ''
}
}
},
The router config
{
path: '/change/detail/:id',
name: 'ChangeDetail',
component: ChangeDetail
}
ChangeDetail
this.$axios.get('api/change?id=' + id)
.then(response => {
......
})
However, I find the url axios is actually calling is,
http://localhost:8080/change/detail/api/change?id=123 instead of http://localhost:8080/api/change?id=123
But when I turn off the history mode, everything is fine when the url is turned to http://localhost:8080/#/change/detail/123.
So what's wrong? Please help me to find a solution for this. Thanks in advance.