API in nodejs Port Issue - node.js

I've created an API in nodejs backend and frontend I used reactjs as I've connected the api to my form
it shows the error
"Could Not proxy request"

Check what is the error in Chrome developer tools. It is most probably CORS issue.
If you are using NodeJs, you can use below command.
res.header("Access-Control-Allow-Origin", "*");
But this will allow CORS for all port running on your machine.
I faced the same issue when using express. I resolved it as shown below :

TRY THIS OUT IN YOUR PACKAGE.JSON CONFIGURATION refereed from create-react-app
"proxy": {
"/api": {
"target": "https://localhost:5002",
"secure": false
}
},
Also try add CORS configuration to your node check this video

Related

Access to localhost was denied You don't have authorisation to view this page. HTTP ERROR 403

I have a little NodeExpress server and when I try to make a request to the server it returns a 403 error
I have installed Cors and used it and tried with chrome browser and Postman as 2 clients and got the same denied error
var express = require('express')
var cors = require('cors')
var app = express()
app.use(cors())
app.get('/', function (req, res, next) {
res.json({msg: 'This is CORS-enabled for all origins!'})
})
app.listen(80, function () {
console.log('CORS-enabled web server listening on port 80')
})
I was having this having this problem with using firebase serve on MacBook Pro (14-inch, 2021), Apple M1 Pro, macOS Monterey 12.3
UPDATE:
so apparently the reason was
macOS Monterey introduced AirPlay Receiver running on port 5000. This prevents your web server from serving on port 5000. Receiver already has the port.
so the solution proposed by the answer quoted above, was to either turn off the AirPlay Receiver, or to run your app on another port.
if you are running your app using firebase serve, You can change the port by following this approach:
source
firebase.json file doesn't work with the the firebase serve command.
You have to use the firebase emulators:start command.
If you want to keep using firebase serve then it should be use like
in:
firebase serve --only hosting --port=5002
OLD ANSWER:
Not a sufficient answer, but I was able to bypass this by entering 127.0.0.1 instead of localhost. I don't think this is the best answer, neither I am satisfied with it. I'll definitely come back later and update the answer once I find a better answer.
just use another port e.g. 5100
"sampleApp": {
"commandName": "Project",
"launchBrowser": true,
"launchUrl": "weatherforecast",
"applicationUrl": "http://localhost:5100",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
Sometimes I had the same issue when developing FLASK application on Monterey and using Chrome.
A restart of Chrome always solved the issue. I suppose that not stopping the application properly is the root cause in my case.
I've just encountered this issue. My stack was Node + Express
With this stack, above solution works as well.
All I had to do was to change the porn number:
app.listen(5000); // does not work
app.listen(8000); // all good :)

Problems running an Angular 9 app in NodeJS

I have a working NodeJS server and an Angular 9 app. I'm able to test the app in development mode, it works perfectly.
But, when I build the app with ng build --prod and try to access it with NodeJS server I get several errors about file load:
Refused to apply style from
'http://localhost:8080/styles.09cf2cc3740ba29d305c.css' because its
MIME type ('text/html') is not a supported stylesheet MIME type, and
strict MIME checking is enabled.
GET http://localhost:8080/runtime.689ba4fd6cadb82c1ac2.js
net::ERR_ABORTED 404 (Not Found)
I have a proxy file in the app to redirect all its petitions to NodeJS:
proxy.conf.json
{
"/api/*": {
"target": "http://localhost:8080",
"secure": false,
"logLevel": "debug",
"changeOrigin": true
}
}
Am I missing something?
proxy.conf.json aims to provide you an easy way to access to backend by rewriting url in development environment, by using ng serve.
For example, by accessing http://localhost:4200/api, in fact, you access http://localhost:3000/api. (so your backend).
But here, you're issue is how to serve Angular files with NodeJS.
Here is a minimal express code which serves an API endpoint /api, and also static files inside public sub-directory.
const express = require('express')
const app = express()
app.use(express.static('public'));
app.get('/api', function (req, res) {
res.send({ message: 'api ok' })
})
app.listen(3000, function () {
console.log('Example app listening on port 3000!')
})
Copy all files generated by ng build --prod, (see inside dist folder, and your-app-name subfolder) to public folder.
node app.js
You will be able to access your Angular app at http://localhost:3000, and your Angular app will be able to access your API at http://localhost:3000/api.

Nestjs server does not serve socket.io client

I have a split app using nestjs on the server and an Angular app as the client. Setting up websockets with socket.io seemed pretty easy using the #nestjs/websockets module and on the client I used ngx-socket-io. I used this repo as basis. Now when I update the project's #nestjs/websockets dependency to the latest version I get
CORS errors and
an error that the client couldn't load the socket.io client js file
I expected CORS problems and after the update, I could fix them by adding
app.enableCors({
origin: 'http://localhost:4200',
credentials: true,
});
to my main.ts file, but I don't know why the client file is not served. With the version of the repo (5.7.x) there are neither CORS errors nor problems with serving the file.
I tried a couple of settings of #WebSocketGateway(), moving to a different port, setting serveClient (even though it should be true by default), but nothing seemed to work. Any advice?
thanks
In my case
I replaced
app.useWebSocketAdapter(new WsAdapter(app));
from
import { WsAdapter } from '#nestjs/platform-ws';
with
app.useWebSocketAdapter(new IoAdapter(app));
in main .ts from
import { IoAdapter } from '#nestjs/platform-socket.io';
Worked like a charm!
The problem was that nestjs did separate the lower level platform (socket.io, express, fastify, ...) from the nestjs modules. The websocket module requires to install an underlying platform, for socket.io
npm install --save #nestjs/platform-socket.io
To serve the socket.io client file it seems like there also needs to be an HTTP platform installed, for express
npm install --save #nestjs/platform-express
More info in the migration guide for v6.
I had the same problem. i was opening the client side of the application in the web-browser, but directly from my filesystem (i would double click on the file index.html next to the little dummy fake-front-end.js on my desktop for example...). It seems that the CORS problem would persist until i actually accessed the index.html through a proper server. So i created a route on my backend, to serve the index.html, and the fake-front-end.js.
There is a section about CORS on the socket.io officual documentation. And there is a section on the nestjs website, but both didnt really helped in my case.

proxy not working for react and node

I'm having issues with the proxy I set up.
This is my root package.json file:
"scripts": {
"client": "cd client && yarn dev-server",
"server": "nodemon server.js",
"dev": "concurrently --kill-others-on-fail \"yarn server\" \"yarn client\""
}
My client package.json file:
"scripts": {
"serve": "live-server public/",
"build": "webpack",
"dev-server": "webpack-dev-server"
},
"proxy": "http://localhost:5000/"
I've set up express on my server side to run on port 5000. Whenever I make a request to the server, ie :
callApi = async () => {
const response = await fetch('/api/hello');
const body = await response.json();
// ... more stuff
}
The request always goes to
Can someone point out what i have to do to fix this issue so that the request actually goes to port 5000?
I experienced this issue quite a few times, and I figured it's because of the cache. To solve the issue, do the following
Edit: #mkoe said that he was able to solve this issue simply by deleting the package-lock.json file, and restarting the app, so give that a try first. If that doesn't resolve it, then do the following.
Stop your React app
Delete package-lock.json file and the node_modules directory by doing rm -r package-lock.json node_modules in the app directory.
Then do npm install in the app directory.
Hopefully this fixed your proxy issue.
The reason the react application is still pointing at localhost:8080 is because of cache. To clear it , follow the steps below.
Delete package-lock.json and node_modules in React app
Turn off React Terminal and npm install all dependencies again on React App
Turn back on React App and the proxy should now be working
This problem has been haunting me for a long time; but if you follow the steps above it should get your React application pointing at the server correctly.
This is how I achieved the proxy calls.
Do not rely on the browser's network tab. Put consoles in your server controllers to really check whether the call is being made or not. For me I was able to see logs at the server-side. My node server is running on 5000 and client is running on 3000.
Network tab -
Server logs -
Check if your server is really running on the same path /api/hello through postman or browser. For me it was /api/user/register and I was trying to hit /api/user
Use cors package to disable cross-origin access issues.
Is your client being loaded from http://localhost:8080?
By default the fetch api, when used without an absolute URL, will mirror the host of the client page (that is, the hostname and port). So calling fetch('/api/hello'); from a page running at http://localhost:8080 will cause the fetch api to infer that you want the request to be made to the absolute url of http://localhost:8080/api/hello.
You will need to specify an absolute URL if you want to change the port like that. In your case that would be fetch('http://localhost:5000/api/hello');, although you probably want to dynamically build it since eventually you won't be running on localhost for production.
For me "proxy" = "http://localhost:5000 did not work because I was listening on 0.0.0.0 changing it to "proxy" = "http://0.0.0.0:5000 did work.
Make sure you put it on package.json in client side (react) instead of on package.json in server-side(node).
This solution worked for me, specially if you're using webpack.
Go to your webpack.config.js > devServer > add the below
proxy: {
      '/api': 'http://localhost:3000/',
},
This should work out.
Read more about webpack devSever proxy: https://webpack.js.org/configuration/dev-server/#devserver-proxy
I have tried to solve this problem by using so many solutions but nothing worked for me. After a lot of research, I have found this solution which is given below that solved my proxy issues and helped me to connect my frontend with my node server. Those steps are,
killed all the terminals so that I can stop frontend and backend servers both.
Installed Cors on My Node server.js file.
npm install cors
And added these lines into server.js file
var cors = require('cors')
app.use(cors())
Into package.json file of frontend or client folder, I added this line,
"proxy" : "http://127.0.0.1:my_servers_port_address_"
Now everything working fine.
Yours might not be the case but I was having a problem because my server was running on localhost 5500 while I proxied it to 5000.
I changed my package.json file to change that to 5500 and used this script:
npm config set proxy http://proxy.company.com:8080
npm config set https-proxy http://proxy.company.com:8080
I am pretty sure just changing it on the package.json worked but I just wanted to let you know what I did.
you should set the proxy address to your backend server, not react client address.
you should restart the client after changing package.json
you should use fetch('/api/...') (instead of fetch('http://localhost:8080/api/'))
Make sure you check your .env variables too if you use them. It's because of that if I was looking for a solution on that page.
I tried all the solutions, proposed here, but it didn't work. Then I found out, that I tried to fetch from root directory (i.e. fetch('/')) and it's not correct for some reason. Using fetch('/something') helped me.
Your backend data or files and react build files should be inside the same server folder.
you must give proxy after the name.{"name":"Project Name", "proxy":"http://localhost:5000"}
port should match with your backend's port.
If you are seeing your static react app HTML page being served rather than 404 for paths you want to proxy, see this related question and answer:
https://stackoverflow.com/a/51051360/345648
(This doesn't answer the original question, but searching Google for that question took me here so maybe this will help others like me.)
In my specific case, I had a both Node backend, and an inner folder with a React project. I tried #Harshit's answer, which didn't work, until I had two package.json files in my project, one in the outer folder, and one in my client (React) folder. I needed to set up the proxy in the inner package.json, and I needed to clear the cache in the inner folder.
I was having this issue for hours, and I'm sure some of the things above could be the cause in some other cases. However, in my case, I am using Vite and I had been trying to add my proxy to the package.json file, whereas it should be added to the vite.config.js file. You can click here to read about it in Vite's docs.
In the end, my code looks like this:
export default defineConfig({
server: {
proxy: {
"/api": {
target: "http://localhost:8000",
secure: false,
},
},
},
plugins: [react()],
});
My problem was actually the "localhost" part in the proxy route. My computer does not recognize "localhost", so I swapped it with http://127.0.0.1:<PORT_HERE> instead of http://localhost:<PORT_HERE>.
Something like this:
app.use('/', proxy(
'http://localhost:3000', // replace this with 'http://127.0.0.1:3000'
{ proxyReqPathResolver: (req) => `http://localhost:3000${req.url}` }
));`
For me, I solved this by just stopping both the servers i.e. frontend and backend, and restarting them back again.
Here is an opinion
Don't use proxies, use fetch directly
not working
fetch("/signup", {
method:"post",
headers:{
"Content-Type":"application/json"
},
body:JSON.stringify(
{
name:"",
email:"",
password:"",
}
)
Actually worked after wasting 6hours
fetch("http://localhost:5000/signup", { // https -> http
// fetch("/signup", {
method:"post",
headers:{
"Content-Type":"application/json" },
body:JSON.stringify(
{
name:"",
email:"",
password:"",
}
)
In my case the problem was that the proxy suddenly stopped to work.
after investigating I found that I've moved the setupProxy from the src folder and that cause the problem.
Moving it back to the src folder have solved the problem.
The problematic structure:
The solution:
faced similar issue. my proxy was not connecting restarting the react app fixed my issue
In my case it was because of typo. I wrote "Content-type": "application/json", (with small t) instead of "Content-Type": "application/json",
you should install this package:
npm install http-proxy-middleware --save
refrense: this link
Make sure your end point match with the backend.

Angular HttpClient fails to proxy

I have a spring boot back-end api and I am trying to call a service for uploading or getting images from angular project. I have a standard proxy.conf.json file:
{
"/api": {
"target": "localhost:8080",
"secure": false,
"logLevel": "debug"
}
}
if my angular service is using Http(HttpModule) everything is ok, but since its deprecated and i want to do it the new way i am trying with HttpClient(HttpClientModule) but in log i am getting :
[HPM] Error occurred while trying to proxy request /upload/ from localhost:4200 to localhost:8080 (ENOTFOUND) (https://nodejs.org/api/errors.html#errors_common_system_errors)
and it is not working. On one try on a linux machine i got the same mistake but with (EINVAL). Can someone guide me what i am doing wrong ? Sorry if the question is stupid there are a few questions like this one but neither of their solutions does not seem to work in my case.
Try to set http protocol in front of the localhost link.
{
"/api": {
"target": "http://localhost:8080",
"secure": false,
"logLevel": "debug"
}
}

Resources