Vue webpack devServer proxy prepending fetch url with vue-router params - javascript

I have vue3 project using a webpack devServer proxy and keep getting a 404 when running a fetch to an api due to the url being prepended with an incorrect value. This only occurs on pages that are using vue-router params.
example page url is -
http://localhost:8081/edit/206
correct fetch url should be -
http://localhost:8000/api/enquiries/getenquiry/206
actual fetch url -
http://localhost:8000/edit/api/enquiries/getenquiry/206
fetch command -
let response = await fetch(`api/enquiries/getenquiry/${id}`, {
method: 'GET',
})
vue-router -
import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
import NewEnquiries from '../views/enquiries/NewEnquiries.vue'
import EditEnquiry from '../views/enquiries/EditEnquiry.vue'
import MailboxesView from '../views/system/mailboxes/MailboxesView.vue'
const routes = [
{ path: '/', name: 'home', component: HomeView },
{ path: '/new', name: 'new', component: NewEnquiries },
{ path: '/edit/:id', name: 'editenquiry', component: EditEnquiry },
{ path: '/mailboxes', name: 'mailboxes', component: MailboxesView }
]
const router = createRouter({
history: createWebHistory(process.env.BASE_URL),
routes
})
export default router
vue.config.js -
const { defineConfig } = require('#vue/cli-service')
const AgentKeepAlive = require('agentkeepalive');
module.exports = defineConfig({
transpileDependencies: true,
devServer: {
proxy: {
'/api': {
target: 'http://localhost:8000',
changeOrigin: true,
logLevel: 'debug',
agent: new AgentKeepAlive({
maxSockets: 100,
keepAlive: true,
maxFreeSockets: 10,
keepAliveMsecs: 100000,
timeout: 6000000,
freeSocketTimeout: 9000000 // free socket keepalive for 9000 seconds
}),
onProxyRes: (proxyRes) => {
const key = 'www-authenticate';
proxyRes.headers[key] = proxyRes.headers[key] && proxyRes.headers[key].split(',');
}
}
}
}
})
What works -
adding the following pathRewrite to remove the prepended "edit" acts a workaround but obviously not a good solution going forward. Where am i going wrong here?
pathRewrite: { '^/edit': '' }

Related

Routes from frontend shown as insecure in https website

I created a webpage using vue.js and on backend node.js.
When I access the main page ( https://example.test ) I got secure info on my browser, but once I go to other links ( https://example.test/dashboard ) I got an insecure connection.
"devServer": {
allowedHosts: ['example.test'],
host: "0.0.0.0",
port: 443,
server : {
type: "https",
options: {
key: fs.readFileSync('/usr/app/key.pem'),
cert: fs.readFileSync('/usr/app/cert.pem')
}},
hot: true
}
Is there any configuration that I'm missing in vue.config.js or I'm missing something in router/index.js?
Vue.use(VueRouter)
const routes = [
{
path: "/sign-in",
name: "signIn",
component: SignIn,
meta: {
requiresNotAuth: true
}
},
{
path: "/dashboard",
name: "dashboard",
component: Dashboard,
meta: {
requiresAuth: true
}
}
]
const router = new VueRouter({
mode: 'history',
base: process.env.BASE_URL,
routes
})
UPDATE
security in https://example.test:
Security in https://example.test/dashboard:

Adonis 5 + Vue "E_ROUTE_NOT_FOUND"

I'm doing an Adonis v5 app with Vue 2 as frontend.
My problem is, once I've build Vue frontend into public adonis folder. If I access to a speficic route writing it into the top browser searcher, I get the E_ROUTE_NOT_FOUND from Adonis.
I do think that adonis is trying to search the route into the router of the server and not into the Vue router. Althought adonis it's configured to use static files and the first frontend page works:
Vue router.js:
Vue.use(VueRouter);
const routes = [
{
path: "/",
redirect: { name: "acceso" },
},
{
path: "/acceso",
name: "acceso",
component: SignupView,
meta: { guestAllow: true },
}];
const router = new VueRouter({
mode: "history",
routes,
});
Adonis routes.ts (It shouldn't affect as the have a prefix:
Route.group(() => {
Route.group(() => {
Route.post("register", "AuthController.register");
Route.post("login", "AuthController.login");
}).prefix("auth");
Route.group(() => {
Route.get("logs", "LogsController.index");
}).middleware("auth:api");
}).prefix("/api");
Adonis static.ts:
import { AssetsConfig } from '#ioc:Adonis/Core/Static'
const staticConfig: AssetsConfig = {
enabled: true,
dotFiles: 'ignore',
etag: true,
lastModified: true,
maxAge: 0,
immutable: false,
}
If I write localhost:3333 on the browser I redirects to /access (Correct)
But if I refresh the page, or browse manually the same route, the error shows
Any idea of what could it be?
Thank you for your time.
After looking some other projects on internet, I've seen that if you use mode: "history" on vue-router it pops the error.
So I've tried to comment this line and now I can refresh the page without E_ROUTE_NOT_FOUND error.
Frontend Vue router.js:
const router = new Router({
//mode: "history",
routes,
});

Adding the proxy in vite takes me to that proxy url on my localhost. I only want to use it for api calls to backend

Here is my vite.config.ts:
import { defineConfig } from 'vitest/config'
import vue from '#vitejs/plugin-vue'
import { quasar, transformAssetUrls } from '#quasar/vite-plugin'
const path = require('path');
// https://vitejs.dev/config/
export default defineConfig({
test: {
globals: true
},
plugins: [
vue({
template: {
transformAssetUrls
}
}),
quasar({
sassVariables: 'src/assets/scss/quasar-variables.sass'
})
],
resolve: {
alias: {
"#": path.resolve(__dirname, './src'),
},
},
server: {
proxy: {
'/socket': {
target: 'wss://abc-website.com:4221/',
changeOrigin: true,
ws: true,
rewrite: (path) => path.replace('^/socket', ''),
},
'/streaming/': {
target: 'https://abc-website.com/',
changeOrigin: true,
},
'/': {
target: 'https://abc-website.com/',
changeOrigin: true,
secure: false,
ws: true
},
}
}
})
whenever my application is loaded it takes me to the https://abc-website.com while being on my locahost port.
I want to use above url for backend api calls only like https://abc-webite.com/api/auth.
Also i set the baseURL to "api/" after setting the proxy in vite.config.ts.
Also after the slight change it calls the REST api like https://localhost:3000/auth, i should rather be https://locahost:3000/api/auth
Vite proxy doesn't seems to work properly for me.
I think you could something like this:
server: {
proxy: {
// ... your other proxies
'/api': {
target: 'https://abc-website.com/',
changeOrigin: true,
secure: false,
ws: true,
rewrite: (path) => path.replace(/^\/app/, ''),
},
}
}
Then all your requests to sites like localhost:3000/api/my-endpoint should be proxied to https://abc-website.com/my-endpoint. You cannot proxy all "basic" requests, 'cause they are reserved for serving everything else, all the assets, index.html's and etc., but I'm also kind

Vue Router production issues

I have a project on Vue.js, and there is some issue with production mode and vue router. On development version I have no issues, but if I compile it and run on production mode, and go to some link - it show me 404 error code
Here is my route js file:
Vue.use(VueRouter)
const routes = [
{
path: '/',
name: 'Home',
component: Home
},
{
path: '*',
name: 'Agents',
component: Agents
},
{
path: '/agents',
name: 'Agents',
component: Agents
},
{
path: '/compare-agents',
name: 'Compare',
component: Compare
},
{
path: '/input',
name: 'InputFields',
component: InputFields
},
{
path: '/check-pay',
name: 'CheckPay',
component: CheckPay
},
{
path: '/success',
name: 'Success',
component: Success
},
]
const router = new VueRouter({
mode: 'history',
base: process.env.BASE_URL,
routes
})
export default router
For example, I wanna go to Agents page, by link like http::/localhost:8080/agents and it's works (dev verison), but if I compile, it's getting 404 error
Website is localted in core directory.
I can visit homepage, use nginx server, and here it's conf file:
worker_processes 4;
events { worker_connections 1024; }
http {
server {
listen 80;
root /usr/share/nginx/html;
index index.html
include /etc/nginx/mime.types;
location / {
try_files $uri $uri/ /index.html;
}
}
}

Why Proxy not working in browser (NuxtJS+Axios)?

In server rendering Proxy is working fine. Request is going to custom-server.com/v1/places. But in browser request is going to current-domain.com/api/places
Why it is not working in browser? Proxy working only in server side? Please, help.
I have NuxtJS config:
require('dotenv').config();
export default {
mode: 'universal',
buildModules: [],
modules: [
'#nuxtjs/axios',
'#nuxtjs/proxy',
['#nuxtjs/dotenv', { systemvars: true }],
],
axios: {
proxy: true,
credentials: true,
},
proxy: {
'/api': {
target: "http://custom-server.com",
pathRewrite: {
'^/api' : "/v1"
},
changeOrigin: true,
},
},
}
My component:
<script>
export default {
data() {
return{
placesServer:false,
placesBrowser:false,
}
},
async asyncData ({ $axios }) {
// Here is all is fine
let response = await $axios.get("/api/places");
return {
placesServer:response.data,
};
},
created(){
if (process.browser){
// Here is not working =(
this.$axios.get("/api/places").then((response)=>{
this.placesBrowser = response.data;
});
}else{
// Here is working fine!
this.$axios.get("/api/places").then((response)=>{
this.placesBrowser = response.data;
});
}
}
}
</script>
If your API URL is =http://custom-server.com/api/v1/api/places
Need to following change of Given code and need to understand the vuejs/Nuxtjs lifecyle
export default {
mode: 'universal',
buildModules: [],
modules: [
'#nuxtjs/axios',
'#nuxtjs/proxy',
['#nuxtjs/dotenv', { systemvars: true }],
],
axios: {
proxy: true,
},
proxy: {
'/api': {
target: "http://custom-server.com",
pathRewrite: {
'^/api' : ""
},
},
},
}
and the given code inside created() hook is need to change another life cycle maybe. or need to move inside method() or as per need your requirements.
adding prefix to axios in nuxt.config.js helped me
axios: {
proxy: true,
credentials: true,
prefix: '/api/'
}

Categories