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.
Related
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
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.
I want to use proxyTable with axios in my vue-cli project.
In my config/index.js, I put code like this:
proxyTable: {
'/getnews': {
target: 'https://xx.xxx.xx.x'
changeOrigin: true,
secure: false,
pathRewrite: {
'^/getnews': '/getnews'
}
}
}
and in my request function, it goes like this:
var url = '/getnews';
this.$axios({
methods: 'get',
url: url,
})
.then(response => {
console.log(response);
})
Now here comes the question, my browser console tells me that
xhr.js?ec6c:178 GET http://localhost:8080/getnews 504 (Gateway Timeout)
and the terminal says:
Error occurred while trying to proxy request /getnews from localhost:8080 to https://xx.xxx.xx.x (ECONNREFUSED)
so it looks like the proxy doesn't work out, my request still goes to my localhost. Anyone knows how to fix that?
I finally figure out with the help of my friend.
It's the lack of port number that causing the problem. The code should be like this:
proxyTable: {
'/getnews': {
target: 'https://xx.xxx.xx.x:8080'
changeOrigin: true,
secure: false,
pathRewrite: {
'^/getnews': '/getnews'
}
}
}
Then it works just fine.
I'm trying to do a post request via https with vue-axios.
However, since i'm using a self-signed certificate that i created, i'm getting the following error:
net::ERR_CERT_AUTHORITY_INVALID
Upon searching i found that most people solve this by doing the following
const instance = axios.create({
httpsAgent: new https.Agent({
rejectUnauthorized: false
})
});
instance.get('https://something.com/foo');
// At request level
const agent = new https.Agent({
rejectUnauthorized: false
});
axios.get('https://something.com/foo', { httpsAgent: agent });
I tried both option but didn't have any success with them.
I used the npm https module for the https.Agent.
Does anyone know how to solve this problem? or should I just change from axios to other modules?
edited:
the piece of code I'm running with the error at the moment:
const axiosInstance = axios.create({
baseURL: 'https://localhost:5000',
httpsAgent: new https.Agent({
rejectUnauthorized: false
}),
});
axiosInstance.post('/user', LoginRequest,
{ headers: { 'Content-Type': 'application/json' } })
.then(response => this.assignLogin(response.data));
tried to change to a module named needle and use https but had the same error:
needle:
const headers = { 'Content-Type': 'application/json' };
const options = {
method: 'POST',
headers: headers,
rejectUnauthorized: false,
requestCert: true,
agent: false,
strictSSL: false,
}
needle.post('https://localhost:5000/user', LoginRequest, options).on('end', function() { })
https:
const options = {
hostname: 'localhost',
port: 5000,
path: '/user',
strictSSL: false,
rejectUnauthorized: false,
secureProtocol: 'TLSv1_method',
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
};
const req = https.request(options, (res) => {
console.log('statusCode:', res.statusCode);
console.log('headers:', res.headers);
res.on('data', (d) => {
this.assignLogin(d);
});
});
req.on('error', (e) => {
console.error(e);
});
req.write(LoginRequest);
req.end();
Since you mention that you are "using a self-signed certificate that you created", I guess that you are using this for local development tests. I had a similar issue, when testing locally in Chrome.
As this error message (net::ERR_CERT_AUTHORITY_INVALID) is a way of Chrome blocking a URL with an "unsafe" certificate, you need to solve this issue through Chrome, telling it that you trust the certificate.
The solution I use is the old one thisisunsafe. (ONLY USE THIS SOLUTION IF YOU REALLY TRUST THE CERTIFICATE, I.E., IT'S YOUR OWN CERTIFICATE):
SOLUTION: Just open a tab in Chrome, try to open a URL with your server address (in your case, https://localhost:5000/). Chrome will display a warning message, so you click anywhere in the window, and type thisisunsafe. Chrome will now allow access to this certificate. When you reload the client again and try to request the server, it will work.
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