React proxy not conecting to api url - node.js

when i am building a social media website, but i have run into a big problem, my api server runs on localhost:6000, and my react app runs on the default of localhost:3000, i have setup my proxy in the react app's package.json to the api url (localhost:6000), but when i make an api call using axios for example
const response = await axios.get("/api/users", body, config);
console.log(response.data);
the front end makes the api call to the localhost:300 url not my api url,
please what can i do to fix this problem it has been bugging me for the past 2 days now lol.

try setting "proxy": "127.0.0.1:6000" in your package.json file for your client.

I have 3 suggestions you could try and follow
axios.get('http://localhost:6000/api/users')
or have you tried adding this to the request?
headers: {
"accepts":"application/json"
}
and finally you could try and use this package
const { createProxyMiddleware } = require('http-proxy-middleware');

const response = await axios.get("http://localhost:6000/api/users", body, config);
console.log(response.data);
Should work, or am I missing something?

Related

Why Am I getting this error 'You need to enable javascript' in my React.js app?

I am getting the you need to enable javascript to run this app error in my MERN stack application. Everything else works fine except for an api call I made for a particular route. I use axios package and all API calls I made in the application are working fine and fetching required data and displayed on my browser. The problem is this particular route. This same route works fine in postman. Here is the code:
useEffect(()=>{
const fetchMenu = async () =>{
try{
const response = await axiosPrivate.get(`/api/v1/menu`, { withCredentials: true,headers:{authorization: `Bearer ${auth}`}
});
console.log(response.data, 'hello menu')
}catch(err){
}
}
fetchMenu()
}, [])
If I call the API via postman, it is fetching the data fine. AxiosPrivate is coming from axios and has been working fine in all places I used it. I really don't know what could be the problem.
The problem was with how I was calling my api. The address should have been /v1/menu instead of /api/v1/menu. This is because in my package.json file already has the proxy this way "proxy": "http://localhost:5000/api/v1",

Post a simple react form - node, axios, nodemailer, backend, postman

I've set up a react form running on http://localhost:3000/about and I've the backend running on port 5000 (localhost:5000). On react's package.json I set up "proxy":"localhost:5000:.
When I use postman and I send the post to localhost:5000/api/contact, the email is sent correctly (I send the data as JSON - name, email and message). Status 200
When I use the react form, the data is well prepared as json but I can't figure out the baseURL to send correctly the method post. status 404. I tried:
localhost:3000/about/api/contact;
localhost:3000/api/contact;
localhost:3000/api.... None works...
FYI
the server is set up with the following middleware and is working ok:
app.use('/api',contactRoute)
the controller is imported and coded as following:
router.post('/contact', (req, res)=>{
const data = req.body;
The React part is not posting correctly with axios and is coded as following:
onSubmit: async (values) => {
//values.preventDefault();
try {
const data = (JSON.stringify(values, null, 2))
setLoader(true);
console.log(data)
await axios.post('/contact', data);
The method post in react is never completed, when I check the console.log of data, is correctly structured as JSON...status 404
use the post parameter in your axois request {port: 5000} then It will use your actual backend port.
By default, axios uses the base path from the URL. So, here when an API request is made.
await axios.post('/contact', data);
It is actually making the post request on localhost:3000 rather than your backend server at localhost:5000. Also, "api" should also be prepended.
One simple way is to use absolute URL which should work.
await axios.post('http://localhost:5000/api/contact', data);

connection between angular and node

I have an angular app and I want to connect to node.js server. My question is how to do that? Do I have to write any code on my angular app to set the connection and then send the http request or just send the requests to the server? (I have all the API's ens points).
When I just send the request I get 404 error.
export class ApiConnectionService {
uri = "http://dev.cantinadigital.co.il:8080";
constructor(private http: HttpClient) { }
postContactUsMessage(message: Object): Observable<any> {
return this.http.post(${this.uri}/contactus, message);
}
}
If you have Angular app working for example on 'localhost:3000' and node server on 'localhost:5000' You have to send request to node server address. So if you want to get for example list of todo's you have to send 'GET' request to 'localhost:5000/todos'. But if it all works on one port, You just send request to '/todos' and that should work well.
You just send a request to your server.
For Example:
public doSomething(): Promise<any> {
var url = "localhost:8081/api/test";
return this.http.get(url, option).toPromise();
}
When you call the function, don't forget its asynchronous:
doSomething().then(result => ....)
Also you have to adjust your proxy settings, so you have to add an entry in proxy.conf.json
If you get a 404 maybe your server setup is not working. So maybe it would be best if you check with Postman, if you can reach your url.
I made a demo for you to how to deal with the Http calls and Api in angular and put you a comment in what you should change to work with your case:
https://stackblitz.com/edit/angular-service-intro?file=src%2Fapp%2Fapp.service.ts
Hope this helps you

create-react-app causing Node.js requests to not go through proxy

I'm currently writing an app with Electron, Create-React-App, and Node.js (note: in electron, webSecurity is disabled to make CORS requests).
In my App.js file I'm trying to write a module to test proxies by sending a request to a site and checking the response, like so
var proxiedRequest=request.defaults({'proxy':"http://username:password#test.test.com:0000"})
await proxiedRequest.get(site, function(error, resp, body){
console.log(resp.statusCode)
console.log(resp)
}
Now I created a separate test.js file that I used to make sure that it was react causing the issues
const request = require('request-promise')
var proxyUrl = //working proxy here;
var proxiedRequest = request.defaults({'proxy': proxyUrl});
proxiedRequest.get('http://google.com',function(err, resp, body){
console.log(err)
console.log(resp.statusCode)
})
And I tested it with both a working and non-working proxy and got the correct responses.
My question is why is create-react-app causing the request to not be routed through the proxy? Is it due to the fact that its being hosted on https://localhost:3000 or is it actually an electron based issue?
you have to add your localhost to your Whitelabel cors in your backend if your API is made by express you can use cors lib to solve the problem cors lib

Express JS: Superagent does not use http-proxy-middleware

I am writing a node application using express JS. Usually in this application we consumes res apis and merge them in one object and send it to angular application.
As a rest client I am using superagent. One of my colleague has written reverse proxy code using http-proxy-middleware.
Using superagent I make a call like below and it does not use http-proxy-middleware as i have mentioned in code.
let request = require("superagent");
request.get("applications-api/1/anotherendpoint")
.set("Content-Type", "application/json")
.set("x-application", applicationId)
.then((response) => {
res.send(response.body);
})
.catch((err) => {
res.json(err)
});
Usually http call should go through middleware since we have that middleware used in express server like but it does not do. In middleware we are using actual endpoint when path matches to "^applications-api", but its not happening. Superagent expecting url which starts from http://endpoint.com/1/anotherendpoint but I want it to be used from proxy-middleware.
Is there anything to do with superagent configuration in order to use http-proxy-middleware ?
Kindly suggest. Any help would be greatly appreciated.
Thanks

Resources