Devserver Proxy w/ Axios - express

I cannot seem to get the devServer: proxy setting working in my vue / express app.
My vue.config.js file is in the root of my client folder and looks like:
module.exports = {
devServer: {
proxy: {
'api': {
target: 'http://localhost:5000'
}
}
},
transpileDependencies: [
'vuetify'
]
}
I'm sending a request from the frontend using axios like this:
const response = await http.get("/api/auth/authenticate");
My express app is running on localhost:5000 and I've configured endpoints as such:
...other endpoints
app.use("/api/auth", authController);
The request appears in my network tab as:
Request URL: http://localhost:8080/api/auth/authenticate
and returns a 404 error.
What am I missing here?

Since now it is not fetching from your backend, but searching for some static content (hitting 8080, vue must be running on this port). Try using, so that it get redirected to proxy:
proxy: {
'^/api': {
target: 'http://localhost:5000',
ws: false,
changeOrigin: true
},
Or just '/api' instead of '^/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.

Why proxy in vue.config.js 404

I have a small front-end and back-end separated project with development environment and production environment, so I want to set the proxy to call api. vue/cli version is 4.6.5.
file structs:
src
axios
api.js
request.js
components
home
LastBlogs.vue
.env.development
.env.production
package.json
vue.config.js
.env.development:
NODE_ENV = 'development'
VUE_APP_BASE_API = '/dev-api'
VUE_APP_API_ADDRESS= 'http://localhost:8080/blog/'
.env.production:
NODE_ENV = 'production'
# base api
VUE_APP_BASE_API = '/api'
# api publicPath
VUE_APP_API_ADDRESS= 'http://localhost:8080/blog'
vue.config.js:
'use strict'
var path = require('path')
module.exports = {
configureWebpack: {
devtool: 'source-map'
},
assetsDir: 'static',
devServer: {
contentBase: path.join(__dirname, 'dist'),
compress: true,
port: 8001,
proxy: {
[process.env.VUE_APP_BASE_API]: {
target: [process.env.VUE_APP_API_ADDRESS], // api地址
changeOrigin: true,
ws: true,
pathRewrite: {
['^' + process.env.VUE_APP_BASE_API]: '/api',
}
}
}
}
}
axios:
import axios from 'axios'
import qs from 'qs'
// import {app} from '../main.js'
console.log(process.env)
/****** 创建axios实例 ******/
const request = axios.create({
baseURL: process.env.VUE_APP_API_ADDRESS,
timeout:5000
})
// some code of interceptors
export default request;
api.js:
import request from './request.js'
var api = process.env.VUE_APP_BASE_API //'/api'
export function getLastBlogs(){
return request({
url: api+'/blog/lastBlogs',
method: 'get'
})
}
I call api in vue file as this:
<script>
import {getLastBlogs} from '#/axios/blogApi.js'
export default {
name: 'LastBlogs',
data() {
return {
blogs: ["AAAA", "BBBB"]
}
},
created: async function(){
let res = await getLastBlogs();
this.blogs = res.data
}
}
</script>
I got 404 at terminal:
error: xhr.js:160 GET http://localhost:8080/blog/dev-api/blog/lastBlogs 404
and the api of back end is ok:
When I put http://localhost:8080/blog/api/blog/lastBlogs in browser, I get this:
{"code":"0","msg":"操作成功","data":[{"id":1,"blogUser":1,"blogTitle":"test1","blogDescription":"for test","blogContent":"ABABABABAB","blogCreated":"2020-09-20T10:44:01","blogStatus":0},{"id":2,"blogUser":1,"blogTitle":"test2","blogDescription":"for test","blogContent":"BABABABABA","blogCreated":"2020-08-20T10:44:01","blogStatus":0}]}
What should I do? Thanks.
So you are configuring Vue CLI dev-server (running on port 8001) to proxy all requests to /api to http://localhost:8080/blog/api (server) but at the same time configure Axios to use baseURL: process.env.VUE_APP_API_ADDRESS ...which means Axios is sending all requests directly to your server instead of proxy...
Just remove that baseURL: process.env.VUE_APP_API_ADDRESS from Axios config
I also believe your pathRewrite option in proxy config is incorrect.
You dispatch request to /dev-api/blog/lastBlogs
Request goes to Vue dev-server (localhost:8001)
Proxy translates /dev-api into http://localhost:8080/blog/dev-api = http://localhost:8080/blog/dev-api/blog/lastBlogs
pathRewrite is applied to whole path part of the URL - /blog/dev-api/blog/lastBlogs - RegEx ^/dev-api will not match
Try to change pathRewrite into [process.env.VUE_APP_BASE_API]: '/api'

Socksjs infinite loop with vue.js

I'm using vue.js with a flask server.
The 8080 vue.js dev env forwards axios queries to port 80 , cause my python flask server is always running on port 80, waiting for web services calls.
This is my vue.js vue.config.js file :
module.exports = {
outputDir: "dist",
// relative to outputDir
assetsDir: "static" ,
devServer: {
proxy: 'http://localhost:80'
}
};
everything works except that Im getting sock-js infinite loops, especially when developping on port 8080 :
How can I stop theses queries, please .
I there any way to only forwards AXIOS queries to port80, not the others things ?
https://github.com/webpack/webpack-dev-server/issues/1021
EDIT : Tried this with no luck
vue.config.js :
module.exports = {
outputDir: "dist",
// relative to outputDir
assetsDir: "static",
devServer: {
proxy: {
"^/api": {
target: "http://localhost:80"
}
}
}
};
error :
Error: Request failed with status code 404
EDIT : Hey Guys, finally resolved with this code , simply write this in your vue.config.js at the root of the vue.js app, so the wrong sockjs-node queries will get ignored, only web services will be forwarded :
module.exports = {
outputDir: "dist",
assetsDir: "static",
devServer: {
proxy: {
"/api": {
target: "http://localhost:80"
}
}
}
};
Then, do an axios query from vue.js like this :
const path = '/api/read_linear_solution';
axios.post(path, this.form)
Then, in ur python or node server , the web service must look like this 👍
#app.route('/api/read_linear_solution', methods=['POST'])

Vue.js - proxy in vue.config.js is being ignored

I have been searching and reading thru documentation on this topic but I was unbale to make it work.
https://cli.vuejs.org/config/#devserver-proxy
I made my Vue.js application normaly by the commnand
vue create my-app
so I'm running the app by command
npm run serve
on http://localhost:8080/. Pretty standart stuff.
But my app needs a PHP backend which is running at https://localhost/
So I setted up the proxy setting in vue.confic.js file in my root directory.
Content of vue.confic.js file:
module.exports = {
devServer: {
proxy: {
'^/api': {
target: 'https://localhost/',
ws: true,
changeOrigin: true
}
}
}
};
And I'm trying to make axios call for the script on the adress
https://localhost/test.php
The axios call is
mounted() {
this.$axios.get('api/test.php', {})
.then(response => { console.log(response.data) })
.catch(error => { console.log(error) });
},
But for some reason which i cant figure out I'm still getting
GET http://localhost:8080/api/test.php 404 (Not Found)
Thank you in advance. I'll be happy for any tips.
Your axios call is going to make the request to the API with whatever protocol the webpage is on.
The error shows that you’re making an http call but your webpack config is only spoofing https. Are you visiting https from the page making the request?
Eg https://localhost:8080
You can also try updating your webpack proxy server to look like this
module.exports = {
//...
devServer: {
proxy: {
'/api': {
target: 'https://other-server.example.com',
secure: false
}
}
}
};
Additional debug steps: curl your Api endpoint from your terminal to see if it’s a protocol issue
you can try
https: true,
proxy: {
'/api': {
target: 'https://localhost/',
ws: true,
changeOrigin: true
}
}
before try, restart by npm run serve to make it sense

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