Error React Proxy error: Could not proxy request - javascript

Why do I got this error:
Proxy error: Could not proxy request /api/v1/management/me from localhost:3000 to http://localhost:8080 (ECONNREFUSED).
Got this axios setting:
axios.defaults.baseURL = "http://localhost:3000/";
And set this in package.json:
"proxy": "http://localhost:8080"
tried also:
"proxy": "http://localhost:8080/"
And have following call:
axios({
method: "get",
url: "api/v1/management/me",
data: {},
headers: { crossDomain: true },
})
When I call directly http://localhost:8080/api/v1/management/me I got response from server.
I have following backend, Vapor route setting. Maybe something wrong / specific here?
let protectedAPIRouter = authSessionRouter.grouped("api/v1").grouped(User.guardAuthMiddleware())
let managementAPIRouter = protectedAPIRouter.grouped("management")

I would suggest the following solutions:
Try to change localhost to IP address: "proxy": "http://your_IP_address:8080"
Try this construction also:
"proxy": {
"/api/*": {
"target": "http://localhost:8080",
"secure": false
}
}

You need to set up a proxy to the backend service you want to access.
First install (http-proxy-middleware) package.
Remove the ("proxy": "http://localhost:8080/") or the Url behind the proxy in the package json file.
In the src folder create a file (setupProxy.js) and and the following code.
const { createProxyMiddleware } = require('http-proxy-middleware');
module.exports = function(app) {
app.use(
'/api',
createProxyMiddleware({
target: 'http://localhost:8080',
changeOrigin: true,
})
);
};

I solved this issue change localhost to 127.0.0.1 in the package.json over the client project.

Related

Webpack Proxy does not work with django backend

I recently had to add webpack to my react app. When i try to fetch from my django backend on http://localhost:9000 i get a "AxiosError Request failed with status code 404". The request does not get to my backend even with the proxy set.
devserver settings
headers: {
"Access-Control-Allow-Origin": "*",
},
proxy: {
"/api": {
target: "http://localhost:9000",
pathRewrite: { "^/api": "" },
secure: false,
changeOrigin: true,
},
},
Am i missing anything ?
I already had the react frontend requesting from my django server before adding webpack.

http-proxy-middleware does not forward any of the path

I am trying to configure a proxy for my API requests using http-proxy-middleware, which the create react app docs suggest. I set up my proxy like this, in the setupProxy.js file:
const { createProxyMiddleware } = require('http-proxy-middleware');
module.exports = function (app) {
app.use(
createProxyMiddleware("/post", {
target: 'https://postman-echo.com',
changeOrigin: true,
logLevel: 'debug'
})
);
};
then, I do a simple POST to an endpoint:
const response = await fetch("/post", {
method: 'POST',
headers: {
'content-type': 'application/json;charset=UTF-8'
},
body: JSON.stringify({ foo1: "bar1", foo2: "bar2" })
});
console.log(await response.json());
According to the http-proxy-middleware docs, I should expect a proxy that does something like this:
[HPM] POST /post -> https://postman-echo.com/post
But instead, the debugger shows this:
[HPM] POST /post -> https://postman-echo.com
The path, /post, does not get appended to the proxy request. The target should actually be https://postman-echo.com/post. My client gets a 404 error because https://postman-echo.com on its own does not match anything on the backend.
If it did reroute correctly, I should expect the same results as a CURL request
curl -X POST -F 'foo1=bar1' -F 'foo2=bar2' https://postman-echo.com/post
{"args":{},"data":{},"files":{},"form":{"foo1":"bar1","foo2":"bar2"},"headers":{"x-forwarded-proto":"https","x-forwarded-port":"443","host":"postman-echo.com","x-amzn-trace-id":"Root=1-61200c54-7b5809be3e78040f09edcd42","content-length":"240","user-agent":"curl/7.64.1","accept":"*/*","content-type":"multipart/form-data; boundary=------------------------bb54b419e41f4a4a"},"json":null,"url":"https://postman-echo.com/post"}%
But I 404 because the path is not added. Why is the path being left out?
I created a simple app that recreates my issue. This looks similar to this issue but they are not the same (I am using the same syntax as the answer suggests).
I got it working. The problem was that I was testing with an endpoint that 404'd. I got confused because the debugger doesn't append /post to the end of the log like the docs say it should.

Webpack devserver proxy not working to get round CORS issue

I have a React app which is running webpackdevserver on port 3000.
I have an AWS .NetCore Lambda server running localhost on port 5050.
When I try and make a request I am getting the cors error:
Access to fetch at 'http://localhost:5050/' 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. If an opaque response serves your needs, set the request's
mode to 'no-cors' to fetch the resource with CORS disabled.
I was hoping to use a proxy, as per the documtation here in order to forward my requests on using the same domain to get round this.
https://medium.com/#drgenejones/proxying-an-external-api-with-webpack-serve-code-and-a-restful-data-from-separate-endpoints-4da9b8daf430
However it is not working, I don't see any difference at all with the settings applied, can anyone help?
devServer: {
port: 3000,
disableHostCheck: true,
compress: true,
host: 'localhost',
proxy: {
'/': {
target: 'http://localhost:5050',
secure: false,
},
},
},
My JavaScript to call the server is like this... I have also tried with the url http://localhost:3000 but this just returns a bad request error.
const result = await fetch('http://localhost:5050', {
method: 'POST',
headers: new Headers({ 'Access-Control-Allow-Origin': '*' }),
body: JSON.stringify({
method: 'upload',
test: 'test',
}),
});
I guess the issue is to set / which could just fetch the current server so you might need to differentiate between your web app vs your server (most likely via a specific path such as /api, but you can choose to pass this path to your proxy server or not).
So you would change as following:
Your configuration of proxy first to take api to go through proxy:
proxy: {
'/api': {
target: 'http://localhost:5050',
pathRewrite: {'^/api' : ''}, // In this case we don't pass `api` path
}
}
Next thing is to change your code to call the same domain + port 3000 normally (proxy would do the rest for you by passing to your server with port 5050 which you configured):
const result = await fetch('http://localhost:3000/api', {
// ...
});

How to set proxy for different API server using Nuxt?

So I have 2 applications:
an Adonis API server accessible via http://10.10.120.4:3333
A SSR app using Nuxt.js accessible via http://10.10.120.4:80
The Nuxt.js app is accessible outside using url http://my-website.com. I have axios module with this config
axios: {
baseURL: '0.0.0.0:3333/api',
timeout: 5000
}
Now the problem is, when I am requesting data with asyncData it works, but when the request was made from outside asyncData, say created() for example, it throws an error saying the url http:0.0.0.0:3333 is missing which is true since it's already running in the browser and not in the server.
The first solution that I've tried is to change the baseURL of the axios module to this
axios: {
baseURL: 'http://my-website.com/api',
timeout: 5000
}
But it seems nuxt server can't find it, so I think the solution is to make proxy and installed #nuxtjs/proxy.
And this is my proxy config in nuxt.config.js
{
proxy: {
'/api': 'http://my-website.com:3333',
}
}
and then I just changed my axios baseURL to
http://my-website.com/api
But again it didn't work.
My question is, how do you deal with this kind of scenario? Accessing different server from browser?
When using Proxy in a nuxt project you need to remove baseUrl and set proxy to true as seen below.
axios: {
// Do away with the baseUrl when using proxy
proxy: true
},
proxy: {
// Simple proxy
"/api/": {
target: "https://test.com/",
pathRewrite: { "^/api/": "" }
}
},
when making a call to your endpoint do:
// append /api/ to your endpoints
const data = await $axios.$get('/api/users');
checkout Shealan article

hapi.js cors with auth

Put together the below.
server.route([
{
method: "POST",
path: "/authorize",
config: {
auth: false,
cors: {
origin: ['*']
}
},
handler: (request, reply) => {
...
reply.redirect(redirectUrl)
}
}
])
I want to use with client-side JavaScript browser fetch API. The cors part is necessary to avoid using the no-cors mode for fetch and to get a non-opaque response.
If I use only 'authin the config section or onlycors` they work fine, but together hapi complaints that the configuration is wrong.
Why is that?
inside config object you cannot use key cors. for correct configuration you have to put cors key inside this like this
server.connection({
port: dbConfig.port,
routes: { cors: true } // set cross origin by hapi inbuilt property
// tls: tls
})

Categories