Proxy not hitting in Nuxt Axios causing CORS - vue.js

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

Related

Backend api call not working in Vue(front)

My environment
front - windows, port 3000
backend - linux (ubuntu) in docker container, port 5000
Vue(front) tsconfig.json
export default defineConfig({
plugins: [vue(), vueJsx()],
resolve: {
alias: {
"#": fileURLToPath(new URL("./src", import.meta.url)),
},
},
server: {
host: true,
port: 3000,
proxy: {
"/api": {
target: "http://127.0.0.1:5000",
changeOrigin: true,
secure: false,
rewrite: (path) => path.replace(/^\/api/, ""),
},
},
},
});
front api call code
const response = await axios.post("http://127.0.0.1:5000/users/login?email=" + code);
backend(Nestjs) - main.ts
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.enableCors({
origin: 'http://localhost:3000',
methods: 'GET,HEAD,PUT,PATCH,POST,DELETE,OPTIONS',
credentials: true,
});
await app.listen(5000);
}
bootstrap();
I expect the api call to go to the backend, localhost:5000
but i get a 404 error
When I tried with postman, I got normal return, but when I sent the request using axios in Vue with the same request, I got 404 not found.
The most incomprehensible thing is that with the current settings, it was normally requested when developing in the past.
I don't know how to fix this
please help a lot
Repositories currently being edited: https://github.com/PracticeofEno/ft_transcendence
thanks
omg... I send POST message..
But api is GET Message

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);
}
});

CSRF token and Nuxt-auth

I'm now trying to code a login functionality using nuxt-auth.
I've got a FastAPI server that is set to work with HTTPOnly cookies, thus it needs a csrf token for throwing a user to my client. I can't handle the token because it's HTTPOnly so no LocalStorage
Login works fine but I can't manage to get the stored user. I made that after request to my /login endpoint, Nuxt also requests a user on /me endpoint. But I'm getting the 401 response and
Missing cookie access_token_cookie
error on /me. I don't know how to handle it.
my login request method
async userLogin() {
await this.$auth.loginWith('cookie', {
data: `grant_type=&username=${this.emailInput}&password=${this.passwordInput}&scope=&client_id=&client_secret=&`,
method: 'POST',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
})
await this.$router.push('/account')
}
I read that nuxt-auth is bad at cookie patterns but the post was from 2018 and we have a 'cookie' strategy now. So is there a workaround of it's better to handle authentication manually?
my auth key in nuxt.config.js
auth: {
strategies: {
cookie: {
endpoints: {
login: {
url: "/api/v1/login/login",
method: "post",
withCredentials: true
},
logout: { url: "/api/v1/login/logout", method: "post" },
user: {
url: "/api/v1/users/me",
method: "get"
}
},
tokenType: "bearer"
}
}
}
I have a working http-only cookie based setup on Nuxt + Django.
My Nuxt application reverse proxies API requests to backend. So, it can read cookies on server side.
So, I create auth-ssr.ts middleware to check is user loggedIn
import { Context, Middleware } from '#nuxt/types'
import { parse as parseCookie } from 'cookie' // this is lib https://github.com/jshttp/cookie
/**
* This middleware is needed when running with SSR
* it checks if the token in cookie is set and injects it into the nuxtjs/auth module
* otherwise it will redirect to login
* #param context
*/
const authMiddleware: Middleware = async (context: Context) => {
if (process.server && context.req.headers.cookie != null) {
const cookies = parseCookie(context.req.headers.cookie)
const token = cookies['session'] || '' // here your cookie name
if (token) {
context.$auth.$state.loggedIn = true
}
}
}
export default authMiddleware
And here my nuxt.config.js
auth: {
strategies: {
cookie: {
user: {
property: 'user',
},
endpoints: {
login: {
url: '/api/v2/auth/login/',
method: 'post',
},
user: {
url: '/api/v2/auth/user/',
method: 'get',
},
logout: {
url: '/api/v2/auth/logout/',
method: 'post',
},
},
},
},
redirect: {
login: '/login',
},
plugins: ['#plugins/axios.ts'],
},
router: {
middleware: ['auth-ssr', 'auth'],
},
// Axios module configuration: https://go.nuxtjs.dev/config-axios
axios: {
proxy: true,
},
proxy: {
'/api': {
target: 'https://backend.com/',
},
},
...

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