Backend api call not working in Vue(front) - api

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

Related

How to transform perfect devServer config file for production server. Because locally no error and after deploy cors error

The below code is working fine locally on chrome and firefox without installing the cors plugin. However, when I create a build and place a static file to a production server droplet at /var/www/html It's not working. Please let me know how to change this config file for production and I don't get cors error as well. like not getting cors or any error locally.
This is my vue.config.js file:
module.exports = {
devServer: {
proxy: {
"/one": {
target: "https://etherscan.io/",
pathRewrite: { "^/one": "" },
},
"/two": {
target: "https://bscscan.com/",
pathRewrite: { "^/two": "" },
},
},
},
};
Moreover, This is the request:
this.$http
.get("http://localhost:8080/one/token/" + this.contractAddress, {
mode: "no-cors",
header: {
"Access-Control-Allow-Origin": "http://localhost:8080/",
},
gzip: true,
})
The second request in the same component is:
this.$http
.get("http://localhost:8080/two/token/" + this.contractAddress, {
mode: "no-cors",
header: {
"Access-Control-Allow-Origin": "http://localhost:8080/",
},
gzip: true,
})
Error after deployment, when I open deployed app by IP address:
Then I tried to replace http://localhost:8080 to http//:localhost in URL and at access control allow origin I placed http://ip or server/ Then Error

createProxyMiddleware not working on Azure Webapp

I'm running an Angular Universal application that is talking to an API. Now I'm trying to set up a proxy in the Universal server that proxies API requests to the actual API server:
server.use(['/api', '/sitemap.txt'], createProxyMiddleware({
target: process.env.API_URL,
onProxyReq: req => {
console.log('Using origin: ' + getOrigin(req.getHeaders()));
req.setHeader('origin', getOrigin(req.getHeaders()));
},
pathRewrite: {'^/api': ''}
}));
This works perfectly when running locally, but when running it on the server (Azure WebApp), it doesn't work. I can see the console log being called in the WebApp logs, but the resulting document is the Angular application with a message "page not found".
I'm totally out of ideas on where to look for solutions.
Edit:
I tried another proxy middleware and it does do the trick. This code works both locally and on Azure.
import * as proxy from 'express-http-proxy';
// ...
server.use(['/api', '/sitemap.txt'], proxy(process.env.API_URL, {
proxyPathResolver: req => {
let url: string = req.url;
if (url.startsWith('/api')) {
url = url.substr(4);
}
return url;
},
proxyReqOptDecorator(proxyReqOpts, srcReq) {
proxyReqOpts.headers['origin'] = getOrigin(proxyReqOpts.headers);
return proxyReqOpts;
}
}));
But it has some other limitations that make it unusable for our project, so I still need this resolved.
I have it working correctly now. This is the current setup:
server.use(
'/api',
createProxyMiddleware({
target: process.env.API_URL,
changeOrigin: true,
headers: {
Connection: 'keep-alive',
},
onProxyReq: (proxyReq, req, _res) => {
proxyReq.setHeader('origin', getOrigin(req.headers));
},
pathRewrite: {
'^/api': '',
},
})
);
So I added changeOrigin and the keep-alive header. I'm not sure which of the two resolved the issue, once I got it to work I never bothered to check it out. I suspect it's the header, though.

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).

Hapi send request to current local server

I have a graphql running on my server. And I have an upload route like this:
server.route({
config: {
cors: {
origin: ['*'],
credentials: true
},
payload: {
output: 'stream',
parse: true,
maxBytes: 50869457,
allow: 'multipart/form-data'
},
},
method: ['POST', 'PUT'],
path: '/uploadAvatar',
handler: (request, reply) => {
const data = request.payload;
data.identity = options.safeGuard.authenticate(request);
// REQUEST TO THE SAME SERVER THIS IS RUNNING ON
}
});
I want to send a request to the same server as I am in if that makes sense.. How to do that?
btw I want to call localhost:3004/graphql if it's running on localhost:3004 but on production it's running on port 80.
You can use hapi's built in server.inject method for handling internal routing, the docs for inject are here