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

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?

Related

Proxy response 304 “We’re sorry but <website> doesn’t work properly without JavaScript enabled. Please enable it to continue.”

When fetching to an external API with the following proxy settings, I get the json response and everything is fine, but only when served locally with npm run serve. When I build the app with npm run build (also with --mode development) and then launch the app from /dist, I get this message in the 304 response.
We're sorry but doesn't work properly without JavaScript enabled. Please enable it to continue
So my promise is empty and also I get this error: Unexpected token < in JSON at position 0.
I also tried to build it into a docker image and I get the same error.
vue.config.js
module.exports = {
publicPath: process.env.NODE_ENV === "production" ? "" : "",
devServer: {
proxy: {
"^/todos": {
target: "https://jsonplaceholder.typicode.com",
changeOrigin: true,
secure: false,
pathRewrite: { "^/todos": "/todos" },
logLevel: "debug",
},
},
},
};
component.vue
async function fetchData() {
try {
fetch(`/todos/1`)
.then((response) => response.json())
.then((messages) => {
console.log("messages: ", messages);
});
} catch (err) {
console.error("err", err);
}
}
I'm using node v17.9.0 (npm v8.7.0) and latest version of #vue/cli

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': '' }
}
}
}
}

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.

CORS blocking client request in Nuxt.js

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

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.