I'm creating an App using Node.js + Express + Express-ws, but I'm getting the following error when I try to send a message after connection:
const fs = require('fs');
const http = require('http');
const https = require('https');
const express = require('express');
const app = express();
/*
const key = fs.readFileSync('./security/server-key.pem', 'utf8');
const cert = fs.readFileSync('./security/server-crt.pem', 'utf8');
const ca = fs.readFileSync('./security/ca-crt.pem', 'utf8');
const credentials = {key: key, cert: cert, ca: ca};
var httpsServer = https.createServer(credentials, app);
*/
var httpServer = http.createServer(app);
httpServer.listen(8443, function(){
console.log('Listening on *:8443 \n');
});
httpServer.on('connection', function(ws) {
ws.on('message', function(message) {
console.log('received: ' + message);
ws.send(message);
});
ws.send('Hi there, I am a WebSocket server');
});
//ROUTES
app.get('/charger/:id', function(req, res){
res.send('<h1>Hello ' + req.params.id + '</h1>');
});
app.get('*', function(req, res){
res.status(404).send('404 — Not Found');
});
The commented part is to verify that I can use later HTPPS without changint too much stuff.
The error is the following:
TypeError: ws.send is not a function
at Server.<anonymous> (index.js:26:5)
at Server.emit (events.js:194:15)
at TCP.onconnection (net.js:1517:8)
From what I can tell, it's because you're not actually using the express-ws package anywhere. Additionally, the httpServer object is an instance of the http.Server class, and has no built-in knowledge of websockets. Even though you call the argument in the callback ws, it's not actually a websocket object -- it's an instance of the http.ClientRequest class, which has no send method, hence the ws.send is not a function error. So, to resolve this, I think you'll need to do something along these lines, per the docs:
const express = require('express');
const app = express();
const expressWs = require('express-ws')(app);
app.ws('/', function(ws, req) {
// Now you have a ws object available
})
Hope that helps, good luck!
Related
Express App showing cannot find after deploying on cPanel. I have tried to sort out this issue also when I write server.listen() it works great but when I write app.listen() it gives cannot find message.
I tried default Node Js code (last 10 lines except app.listen() ) which works fine while app.listen() not working:
const express = require("express");
const multiparty = require('multiparty');
const mongoose = require("mongoose");
const morgan = require('morgan');
const { createHttpTerminator } = require('http-terminator');
const fs = require('fs');
const cors = require('cors');
const crypto = require('crypto');
require('dotenv').config();
const { MongoClient, ServerApiVersion } = require('mongodb');
const {Product, Service, Home, HireMe } = require('./models/Product');
const app = express();
app.use(morgan('tiny'));
app.use(express.static('public'));
app.use(express.json());
app.use(cors());
app.get('/', (req, res) => {
res.send('Home Page...!');
});
app.get('/offers', async (req, res) => {
try {
const result = await Product.find({});
res.send("result");
} catch (err) {
res.send({ 'error': err.message });
}
})
var http = require('http');
var server = http.createServer(function(req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
var message = 'It works!\n',
version = 'NodeJS ' + process.versions.node + '\n',
response = [message, version].join('\n');
res.end(app);
});
server.listen(); //It works
app.listen (); // Showing Cannot find message
I solved this error by prefixing the URL link (on which I created node JS on cPanel) to routes. Now it works great.
This is what I have, the filename "pages" actually exists
The code is:
var cors = require('cors');
var express = require('express');
var url = require('url');
var fs = require('fs');
var app = express();
var server = app.listen(3000, function () { console.log('Listening to port 3000') });
app.use(cors());
app.use(express.static('pages'));
app.post('/storeData', storeData);
function storeData(req, res) {
var input = url.parse(req.url, true).query;
var to_save = input.email + ',' + input.password + '\n';
fs.appendFile('./loginDetails.txt', to_save, (err) => {
if (err) console.log('Error occured while storing data!');
res.send('Data stored successfully');
});
}
The Error (in browser):
Cannot GET /
You haven't defined a get route for /. If you try to access a file under pages instead of just the root service, it should work.
i am trying to send an https request from my frontend (reactjs) to backend (nodejs/express).
These two both run in localhost.
Back end server code:
const app = require('./app')
const https = require('https');
const fs = require('fs');
const credentials = {
key: fs.readFileSync('key.pem'),
cert: fs.readFileSync('cert.pem')
};
//connect to the database
require('./db')
const port = 8765;
app.get('/', (req, res) => {
res.send('Now using https..');
});
var server = https.createServer(credentials, app);
//var server = https.createServer(app);
// listen for requests
server.listen(port, () => {
console.log("server starting on port : " + port)
});
front end request:
const {data: Sessions}= await axios.get("https://localhost:8765/...");
doint this request from postman with the exact same parameters produces the desired result.However when i try to do this from frontend i get:
GET https://localhost:8765/... net::ERR_CERT_AUTHORITY_INVALID in react chrome extention.
Why is this happening and how can i solve this?
I tried many times but am getting the following error
http://localhost:3001/getLocaiton net::ERR_CONNECTION_REFUSED and
createError (createError.js:17) at XMLHttpRequest.handleError
(xhr.js:87.
How can I solve this issue.
axios.post ('http://localhost:3001/getLocaiton' , {
name: keyWord,
})
.then (function (response){
console.log (response);
})
.catch (function (error){
console.log (error)
});
Following is the code for node back-end
const express = require ('express');
const bodyParser = require ('body-parser');
const cors = require ('cors');
const Client = require('node-rest-client').Client;
const client = new Client ();
const http = require('http')
const app = express ();
app.use(cors())
app.use (bodyParser.urlencoded ({extended :false}))
app.use(bodyParser.json());
const server = http.createServer(app)
server.listen(port)
app.post ('/getLocaiton' , (req, res) =>{
const typeWord = req.body.name;
client.get ('https://api.adform.com/v1/help/buyer/advertisers= '+typeWord+"&key=", function (data, response){
console.log (data);
console.log (response);
})
})
app.listen (3001, ()=> {
console.log ("listining to port 3001")
})
I do not know why you are starting two servers instances by listening on two ports, but I commented out first port listening and you must return respond to your /getLocaiton request (by the way there is a typo in path name):
const express = require ('express');
const bodyParser = require ('body-parser');
const cors = require ('cors');
const Client = require('node-rest-client').Client;
const client = new Client ();
const http = require('http')
const app = express ();
app.use(cors())
app.use (bodyParser.urlencoded ({extended :false}))
app.use(bodyParser.json());
// const server = http.createServer(app)
// server.listen(port)
app.post ('/getLocaiton' , (req, res) =>{
const typeWord = req.body.name;
client.get('https://api.adform.com/v1/help/buyer/advertisers='+
typeWord+
"&key=",function (data, response){
console.log (data);
console.log (response);
// you must return your response to your request
res.json({
data: data
})
}
)
})
app.listen (3001, ()=> {
console.log ("listining to port 3001")
})
Is there any way to send error to frontend on mongoDb connection error.I had tried in a different different way but I didnt get a solution.
var express = require('express');
var session = require('express-session');
var MongoDBStore = require('connect-mongodb-session')(session);
var store = new MongoDBStore(
{
uri: config.connectionString,
collection: 'tbl_session'
});
// Catch errors
store.on('error', function(error) {
app.get('/',function(req,res){
res.send('NOT Connected....')
});
});
You can use web sockets to push this information to the UI.
const express = require('express');
const app = express();
const path = require('path');
const server = require('http').createServer(app);
const io = require('../..')(server);
const port = process.env.PORT || 3000;
var session = require('express-session');
var MongoDBStore = require('connect-mongodb-session')(session);
var store = new MongoDBStore(
{
uri: config.connectionString,
collection: 'tbl_session'
});
// Catch errors
store.on('error', function(error) {
socket.emit('mongodb-failed', error)
});
});
server.listen(port, () => {
console.log('Server listening at port %d', port);
});
// Routing
app.use(express.static(path.join(__dirname, 'public')));
io.on('connection', (socket) => {
// when socket emits 'mongodb-connection-failed', this listens and executes
socket.on('mongodb-failed', (data) => {
// we tell the client to execute 'new message'
socket.broadcast.emit('mongodb-connection-failed', {
errorDetails: data
});
});
});
now at client side:
var socket = io();
socket.on('mongodb-connection-failed', () => {
console.log('you have been disconnected');
//do more whatever you want to.
});
This above example is using socket.io.
You can use any web socket library, see more here