CORS with axios - vue.js

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: {
'^/': ''
}
}
}
}
}

Related

Cors error - ngrok & express & axios issue when trying to make POST request to the server

I am experiencing an issue when trying to make POST request to the server.
both frontend and backend are ngrok hosting.
this is the POST request:
export async function createTest(test: any) {
try {
const res = await axios.post(
`${backendDomain}/test`,
{id: test, name: 'test'},
{
headers: {
'Access-Control-Allow-Origin': '*',
'Content-Type': 'application/json',
'Access-Control-Allow-Methods': 'POST',
},
}
)
const newTest = res.data
return newTest
} catch (error) {
console.log(error)
}
}
this is the backendDomain: https://sd21-23-221-223-216.ngrok.io
Backend:
const corsOptions = {
origin: "https://dz23-12-256-124-663.eu.ngrok.io",
methods: ['GET', 'PUT', 'POST', 'HEAD', 'DELETE', 'OPTIONS'],
allowedHeaders: ['Content-Type', 'Authorization', 'Origin', 'Access-Control-Allow-Origin'],
credentials: true,
}
app.use(cors(corsOptions))
Error:
Access to XMLHttpRequest at 'https://sd21-23-221-223-216.ngrok.io/test' from origin 'https://dz23-12-256-124-663.eu.ngrok.io' has been blocked by CORS policy:
Request header field access-control-allow-methods is not allowed by Access-Control-Allow-Headers in preflight response.
More wierd is that I also have GET request which sometimes work and sometimes not.
any ideas?
You need to add this header param ngrok-skip-browser-warning with any value
Example:
$.ajax({
url: 'https://5120-143-202-253-244.eu.ngrok.io/api',
type: 'GET',
headers: {
"ngrok-skip-browser-warning":"any"
},
success: function (data) {
console.log(data);
}
});

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.

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!!

Access to XMLHttpRequest at 'https://***' from origin 'http://localhost:3000' has been blocked by CORS policy

I'm trying to send a request with axios but I have CORS problem,
this is my nuxt.config.js
plugins: [
"#/plugins/axios/apiService.js",
],
modules: [
'#nuxtjs/axios',
'#nuxtjs/proxy',
],
axios: {
baseURL: process.env.API_URL,
proxy: true,
credentials: false
},
proxy: {
'/api': {
target: 'https://dev.mobit.ir/api/web/v4',
pathRewrite: {
'^/api' : '/'
},
changeOrigin: true,
}
},
and this is my apiService
import axios from "axios";
import { API_URL} from "./config";
export const axiosInstance = axios.create({
headers: {
Accept: 'application/json',
}
});
//Set base url for axios requests
axiosInstance.defaults.baseURL = API_URL;
export const ApiService = {
//resource: api address
get(resource, params = "") {
return axiosInstance.get(resource, {params}).catch(error => {
throw new Error(`[RWV] ApiService ${error}`);
});
},
post(resource, params) {
return axiosInstance.post(`${resource}`, params);
}
};
I tried to set proxy according to nuxt documentation but it doesn't work,
If I use a proxy like https://cors-anywhere.herokuapp.com/ it will works but what why nuxt proxy doesn't work? and I think it's not the correct way.
Do I have to use cookie or middleware?
according to the link below, we should use an array in our module's array for defining proxy like this:
['#nuxtjs/proxy', { pathRewrite: { '^/api' : '/api/web/v4' } }]
link to read more:
https://github.com/nuxt-community/proxy-module
In this type of CORS problems using extensions like link below can solve it until publish it in main domain
https://chrome.google.com/webstore/detail/allow-cors-access-control/lhobafahddgcelffkeicbaginigeejlf?hl=en#:~:text=Allow%20CORS%3A%20Access%2DControl%2DAllow%2DOrigin%20lets%20you,default%20(in%20JavaScript%20APIs).

CORS issue with 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.