CORS issue with Vue js - vue.js

I used vuejs, with address http://localhost:8000.
When calling api, I get CORS error. Sid not succeed request headers
request
Domain from origin http://localhost: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.
let headers = {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': true,
};

You need to create a "vue.config.js" with proxy configuration.
Example :
module.exports = {
devServer: {
proxy: {
'/api': {
target: 'http://localhost:8080',
ws: true,
changeOrigin: true
}
}
}
}

Three Options
Option 1. Edit Vue.config.js
module.exports = {
devServer: {
proxy: {
'/api': {
target: 'http://localhost:8081',
ws: true,
changeOrigin: true
}
}
}
}
Option 2 (Temporary/Test use case)
Use Cors Plugin in chrome Eg- Moseif CORS
Degrade your chrome version less than 71
Use chromium or Canary Browser.
Option 3
Look into your server Cors allowed or not you can add plugin for python cors and annotation for java on server to allow this call.

Related

Is there any solution to solve CORS error in Vite js? [duplicate]

This question already has answers here:
XMLHttpRequest cannot load XXX No 'Access-Control-Allow-Origin' header
(11 answers)
Closed 9 months ago.
I tried all the solutions which were provided by developers for the same issue. I updated the Vite.config.js file like that-
//vite.config.js
export default defineConfig({
plugins: [vue()],
resolve: {
alias: {
'#': resolve(__dirname, 'src'),
},
},
server: {
proxy: {
'/api': {
target: 'http://localhost:3000/',
changeOrigin: true,
secure: false,
rewrite: (path) => path.replace(/^\/api/, '')
},
cors:false
},
},
define: {
'process.env': {}
}
})
I added header properties in both files-
//Login.vue
const header = {
headers: {
'Authorization': 'Bearer ${accessToken}',
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': '*',
'Access-Control-Allow-Methods': POST, GET, OPTIONS,
'Access-Control-Allow-Credentials': true,
'Sec-Fetch-Mode': no-cors,
'Sec-Fetch-Site': same-site
},
//App.vue
const header = {
headers: {
'Authorization': `Bearer ${accessToken}`,
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': '*',
'Access-Control-Allow-Credentials': true,
'Sec-Fetch-Mode': no-cors,
'Sec-Fetch-Site': cross-site,
},
But, when I inspect the code and see under the network header property-
How can I change these header properties or any other way to solve this CORS problem. I want to solve for the frontend side only. Currently, I am running this application in Chrome by disabling security
chrome.exe --user-data-dir="C://Chrome dev session" --disable-web-security but I want to run it to all the browsers without disabling security.
Get Error-
Any valuable suggestion will help me a lot. Thanks in advance
First, you do not need the 'Access-Control-...' headers on the client side. So you can remove these. You can only set CORS on the server side, in your case this is the Vite server.
You defined a proxy on in the Vite server, but I think you made a mistake there. The target must be the url of the real api server, for example https://example.com/realApi.
Next, in your Vue app, you need to call the api with the local url of your Vite dev server, usually http://localhost:3000 and use /api as the path. Vite will rewrite the url like:
http://localhost:3000/api/TheApiYouAreCalling --> https://example.com/realApi/TheApiYouAreCalling
See vite docs server.proxy and node-http-proxy docs for options.
Hope this helps.
Edit:
If you need a proxy in production, you can fairly easy build a node.js proxy with http-proxy. The code below is an example, where your proxy is located at /proxy on your server. The downside may be that you need to run node.js on your server. The example below is using http, for https see http-proxy docs.
var http = require("http");
var httpProxy = require("http-proxy");
var proxy = httpProxy.createProxyServer({});
const server = http.createServer(function (req, res) {
if (/^\/proxy\/api/.test(req.url)) {
req.url = req.url.replace(/^\/proxy\/api/, "");
proxy.web(req, res, {
target: "https://example.com/realApi",
changeOrigin: true,
secure: false,
});
} else {
res.writeHead(200, { "Content-Type": "text/plain" });
const response = "Proxy running...";
res.end(response);
}
});
server.listen(8080);
You cannot solve CORS on front-end.

Nuxt: wrong Axios base URL in client side API requsets

I have set axios Base_url like this in Nuxt config
axios: {
baseURL: process.env.API_URL,
},
the problem is that when i requset api in client side, axios uses default base_url ,
i mean it sends requests to http://localhost:3000/ not to my backend server .
But for requests in server side everything is ok .
the below pic shows client side request .
Try setting Up proxy for the APIs . (In network tab the url will show up as it is shown in the question image)
axios: {
baseURL: process.env.API_URL, // Must be base url
proxy: process.env.NODE_ENV === 'development'
}
proxy:
process.env.NODE_ENV === 'development'
? {
'/': {
target: process.env.API_URL,
changeOrigin: true,
logLevel: 'debug',
secure: false
}
}
: false,

Proxy not hitting in Nuxt Axios causing CORS

I am receiving following CORS error
Access to XMLHttpRequest at 'https://gw.bilinfo.net/listingapi/api/export' from origin 'http://localhost:3000' 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.
My Nuxt.config.js looks like this:
proxy: {
'/listingapi/api/export/': {
target: 'https://gw.bilinfo.net/',
pathRewrite: { '^/listingapi/api/export/': '' },
changeOrigin: true
}
},
axios: {
proxy: true,
baseURL: 'http://localhost:3000', // Used as fallback if no runtime config is provided
withCredentials: true,
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
}
},
My data fetching component looks like this:
async fetch() {
const data = await this.$axios.$get(
'https://gw.bilinfo.net/listingapi/api/export',
{
credentials: true,
auth: {
username: 'XXXXXXX',
password: 'XXXXXXX'
}
}
)
this.biler = data.Vehicles
},
Everything works fine on refresh, but clicking around the website, gives a CORS error an data disappears. Somehow I am not hitting the proxy, but I can't understand why.
while proxying you have to call it below way
async fetch() {
const data = await this.$axios.$get(
'/listingapi/api/export',
{
credentials: true,
auth: {
username: 'XXXXXXX',
password: 'XXXXXXX'
}
}
)
this.biler = data.Vehicles
}
Below proxy pass code means whenever you want to hit https://gw.bilinfo.net/Example API URL than you have to call it /listingapi/api/export/Example
proxy: {
'/listingapi/api/export/': {
target: 'https://gw.bilinfo.net/',
pathRewrite: { '^/listingapi/api/export/': '' },
changeOrigin: true
}
},
Basically, what you add as pathRewrite will be replaced with the target URL.
Hope this will help!!

CORS with axios

I'm trying send a get request to a valid server using axios an vue.js but I keep getting Access to XMLHttpRequest at 'http://37.152.185.50:8080/hotels/tblisi' from origin 'http://localhost:63342' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. I've tried setting the Content-Type header but no luck. I have the same issue with axios and vue.js in another project too which is apparently working fine for others.
vm = new Vue({
el: '#main-container',
data: {
city: 'istanbul',
hotels: []
},
methods: {
setCity: function (city) {
this.city = city;
axios({
method: 'get',
data: {},
url: 'http://37.152.185.50:8080/hotels/' + this.city,
headers: {
'content-type': 'application/x-www-form-urlencoded',
}
});
}
}
});
Also I don't have access to the server to change the response headers.
The 'Access-Control-Allow-Origin' is type of response header and this must be set by the server.
So you need to change the server's CORS policy to allow your origin: http://localhost:63342 .
You can use Proxy server to avoid CORS Error.
Write this codes at vue.config.js.
module.exports = {
devServer: {
proxy: {
'/': {
target: 'http://localhost:8080',
changeOrigin: true,
pathRewrite: {
'^/': ''
}
}
}
}
}

Vue devServer proxy is not helping, I still get CORS error

I'm using #vue/cli 3.x and in my vue.config.js I have this:
devServer: {
proxy: {
"/api": {
ws: true,
changeOrigin: true,
target: "http://localhost:8080"
}
}
}
But I keep getting CORS error:
Access to XMLHttpRequest at 'http://localhost:8080/api' from origin
'http://localhost:3000' has been blocked by CORS policy: No
'Access-Control-Allow-Origin' header is present on the requested
resource.
Any idea?
It looks like the problem was with the axios configurations.
I had this definition: axios.defaults.baseURL = "http://localhost:8080/api";
I changed it to axios.defaults.baseURL = "api";
and it works.
module.exports = {
...
devServer: {
proxy: {
"^/api": {
target: url,
ws: true,
changeOrigin: true
}
}
},
}