Nestjs server does not serve socket.io client - nestjs

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.

Related

How to combine vue-cli development mode with server-side api?

I'm new to vue and kind of confuse here.
I'm using vue-cli to build a vue app, I understand I can run a development server with npm run serve which is referenced as a script in my package.json for vue-cli-service serve
But my app need some data coming from a local node.js server. I cannot request this server from development mode because it's running on a different server.
To make my app work I'm obligated to build for production with
npm run build
Then to ask my node server to render by default the produced index.html file.
How could I combine development mode and my node server?
What would be the best way to make this work?
Thanks a lot
I stumbled across this, and found the answer buried at the bottom of the comments list, so I thought I'd highlight it.
This answer is taken from #Frank Provost comment, which really should be the accepted answer. As mentioned in his link https://cli.vuejs.org/config/#devserver-proxy all you need to do is create/edit vue.config.js file in your (client) project root to include this:
module.exports = {
devServer: {
proxy: 'http://localhost:3000' // enter dev server url here
}
}
Then start your dev server as usual from your server project:
[server-root]$ npm run dev
And run your client project from vue-cli project
[client-root]$ npm run serve
Then when you visit the client url (usually localhost:8080) all api requests will be forwarded to your dev server. All hot module replacement still works on both client and server.

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.

vue files without NodeJS?

I want to host my app outside of node JS, but I want to use .vue files and possible npm as build system (if it's needed). Is it's possible to do?
I do not need any backward compatibility and if it work on latest Chrome dev it's ok for me.
Is there any examples how it can be done?
I tried to build some webpack template, but it's work only inside NodeJS. On other server I am getting 404 when I am accessing to URLs that placed in .vue files. It's seems that they can't be handled by the other server.
VueJS app is not NodeJS app.
VueJS app is interpreted by the browser.
You just have to build your app on computer and host files as any static website, so any server can serve html and files.
To build your app use e.g. Webpack (https://github.com/vuejs-templates/webpack )
NodeJs only use to build *.js files in front-end, your WebApp dosen't have to run on Nodejs.
1, You can create a index.html file that requires *.js file when webpack built it.
2, Use Chrome to open your index.html file so you can see it works.
You don't need to use vue-cli or other servers if you only want a static page.
But you have to know how to set your webpack.config.js, you can look that doc https://webpack.js.org/guides/getting-started/
Your starting point is wrong. Vue + node.js can build a complete site. Vue is the front-end framework, node's server language. The two can be used in combination. But not vue must rely on node to use. The two of them can be perfect to achieve the front and back separation of the development model.
In projects that use vue, individuals do not recommend configuring webpack and vue-loader separately. You can directly use vue official scaffolding, vue-cli. Do not have to consider these configurations, automatically configured.
Vue-cli
If you just started learning Vue, here's an entry-level demo. Although it is only a small application, but it covers a lot of knowledge points (vue2.0 + vue-cli + vue-router + vuex + axios + mysql + express + pm2 + webpack), including front-end, back-end, database and other sites Some of the necessary elements, for me, learning great significance, would like to encourage each other!
Vue Demo
Best way to develop Vue app is run dev server, and after all just build static assets. You don't need use vuex files, even better is use static template because you can easily integrate it with some back-end (WordPress or whatever).
Helpfully will be use some starter, for ex. Vue.js starter
It's true that vue will create static html pages when you run the build script. However, you will need to serve the files from a small server for the site to work. If you notice, when you run npm run build, the terminal will print a notice...
Tip:
Built files are meant to be served over an HTTP server.
Opening index.html over file:// won't work.
You can create a simple http server in your /dist directory with express and then host your site somewhere like Heroku.
Take a look at this article https://medium.com/#sagarjauhari/quick-n-clean-way-to-deploy-vue-webpack-apps-on-heroku-b522d3904bc8#.4nbg2ssy0
TLDR;
write a super simple express server
var express = require('express');
var path = require('path');
var serveStatic = require('serve-static');
app = express();
app.use(serveStatic(__dirname));
var port = process.env.PORT || 5000;
app.listen(port);
console.log('server started '+ port);
add a postinstall script in a package.json within /dist
{
"name": "myApp",
"version": "1.0.0",
"description": "awesome stuff",
"author": "me oh my",
"private": true,
"scripts": {
"postinstall": "npm install express"
}
}
push only your /dist folder to heroku after you've compiled your site.
proof: I've followed these steps to host my vue.js project
using vue files without NodeJS (nor webpack) is possible with vue3-sfc-loader.
vue3-sfc-loader
Vue3/Vue2 Single File Component loader. Load .vue files dynamically at runtime from your html/js. No node.js
environment, no (webpack) build step needed.
vue3-sfc-loader will parse your .vue file at runtime and create a ready-to-use Vue component.
disclamer: author here
Could you try something as simple as an S3 bucket setup for web serving? How big is your project? How much traffic do you think you'll get? If it's very small, you may be able to host on S3 and use webpack, etc.

Node webpack dev server failing 'Cannot GET /' in vuejs project

I am getting a super unhelpful message 'Cannot GET /' printed to my browser when I run my node dev server through webpack. I am building a Vuejs application with the following:
VueJs structured in a way that was dicated by this Vue Template with my node scripts being identical to the default commands
Webpack config based on Vue Loader
Routes handled through Vue Router
I know this is not a great deal to go off but an idea of what is firing this error (Node? Webpack? Vue Router?) it would point me in the right direction and be greatly appreciated.
If you're experiencing this with Vite, make sure you ran just vite in your package.json script, NOT vite preview
I found myself in the same problem. In my case it was related to the use of Express with Vue.js. So I am leaving my solution in case anyone finds it useful
I added this code for handling the calls to my index.html file
app.route('/*')
.get(function(req, res) {
res.sendFile(path.join(__dirname + '/dist/index.html'));
});
module.exports = app;
Node is throwing the error and make sure your vue router is configured properly,Cannot GET simply means you have not assigned a view to your url e.g on express we use
app.use('/', your route)
and on connect we use
app.get or app.post
All it's saying is there is no content/view assigned to that url.
It turns out it was an issue with the vuejs webpack template I was working from: https://github.com/vuejs-templates/webpack
The build path was being used in the dev server configuration.
Made this pull request to fix the issue: https://github.com/vuejs-templates/webpack/pull/188#issuecomment-230968416
I had this issue while running my app in dev. Adding this to the devServer of my webpack.dev.config file helped:
historyApiFallback: true
Answer by Jezperp here.
If you are using express check that you have this line:
app.use(express.static('static'));
And that "static" matches with the folder specified in your vue.config.js
outputDir: path.resolve("../Server/static")

Parse server error "Protocol not supported"

I've been migrating datas for two days now, everything is ok in AWS - I used a Bitnami MEAN machine, it was only a very small app.
FYI, I'm moving from Heroku + Parse, set up also nginx on AWS to run more than one nodejs app.
I had to downgrade the default mongodb installation due to incompatibility with Parse (WHY?)
So, straight to the problem: installed node.js parse server, configured like they show on git
var api = new ParseServer({
databaseURI: 'mongodb://127.0.0.1:27017/database',
cloud: './cloud/main.js',
appId: 'my-app-id',
masterKey: 'my-master-key'
});
but when I try to execute any query I got
Error: Protocol not supported.
at send (/opt/bitnami/apps/bellboy-admin/node_modules/xmlhttprequest/lib/XMLHttpRequest.js:299:15)
at dispatch (/opt/bitnami/apps/bellboy-admin/node_modules/parse-server/node_modules/parse/lib/node/RESTController.js:137:11)
at Object.ajax (/opt/bitnami/apps/bellboy-admin/node_modules/parse-server/node_modules/parse/lib/node/RESTController.js:139:5)
at ParsePromise.<anonymous> (/opt/bitnami/apps/bellboy-admin/node_modules/parse-server/node_modules/parse/lib/node/RESTController.js:208:29)
at ParsePromise.wrappedResolvedCallback (/opt/bitnami/apps/bellboy-admin/node_modules/parse-server/node_modules/parse/lib/node/ParsePromise.js:135:41)
at /opt/bitnami/apps/bellboy-admin/node_modules/parse-server/node_modules/parse/lib/node/ParsePromise.js:196:35
at runLater (/opt/bitnami/apps/bellboy-admin/node_modules/parse-server/node_modules/parse/lib/node/ParsePromise.js:180:12)
at ParsePromise.then (/opt/bitnami/apps/bellboy-admin/node_modules/parse-server/node_modules/parse/lib/node/ParsePromise.js:195:9)
at Object.request (/opt/bitnami/apps/bellboy-admin/node_modules/parse-server/node_modules/parse/lib/node/RESTController.js:201:8)
at Object.find (/opt/bitnami/apps/bellboy-admin/node_modules/parse-server/node_modules/parse/lib/node/ParseQuery.js:1141:27)
I tried almost everything, any ideas from you?
Did you install the dependencies for ParseServer? More specifically, is the MondoDB NodeJS drive installed?
npm install mongodb
If it helps, I have a tutorial that explains how the ParseServer should be setup, providing you have MongoDB and NodeJS already installed to the correct versions.
Solved
I guessed it was something involving the http/https protocols between my node app and parse server so I just added the http:// before the address of Parse.serverURL
Parse.initialize('my-id','unused');
Parse.serverURL = 'http://localhost:3030/parse';
Maybe it goes by default on https when not specified.

Resources