Q: js file showing me the content instead executing it - javascript

I installed node on my web host but when I enter for example :
www.example.com:3000/server.js
it's showing me the file content instead of executing it
and giving me timeout!
Source:
const http = require('http');
const port = 3000;
const server = http.createServer(function (req, res){
res.write('Hello node')
res.end
})
server.listen(port,function (error){
if (error) {
console.log('err',error)
}else {
console.log('server port',port)
}
})
the output from the website:
const http = require('http');
const port = 3000;
const server = http.createServer(function (req, res){
res.write('Hello node')
res.end
})
server.listen(port,function (error){
if (error) {
console.log('err',error)
}else {
console.log('server port',port)
}
})
The output from the console:
server port 3000
What should the output be:
Hello node
note:
I did lunch it with node and entered the ports*

So the answer is when I called the support of godaddy.com I gave him the issue, after checking my hosting he says that my hosting plan not supporting root or super user, and node.js requires superuser privileges, so by the end i want to thank all of the people who tried to help me, thank you so much.

Related

How to get Express to output random question from my local JSON

I have a local server that I have created to learn and practice my backend coding. Right now its in the early stages. My code is just a basic express app, i can require the json file in and i can display it but what im not sure how to do is every time the page is refreshed to load a different question?
app.js
const express = require('express')
const questions = require('./question.json')
const app = express()
const PORT = 3000
app.get('/', (req, res)=>{
res.set('Content-Type', 'text/html');
res.status(200).send("<h1>Hello</h1>");
})
app.listen(PORT, (error) =>{
console.log(`Server is Successfully Running, and App is listening on port ${PORT}`)
})
questions.json
{
"questions":[
{
"1":"Question 1?"
},
{
"2":"Question 2?"
},
{
"3":"Question 3?"
},
{
"4":"Question 4?"
}
]
}
That should work, you might want to define the path of the questions array first instead of having it written out long handed.
const express = require('express')
const questions = require('./questions.json')
const app = express()
const PORT = 3000
app.get('/', (req, res)=>{
JSON.parse(JSON.stringify(questions))
var randomObject = questions.questions[Math.floor(Math.random() * questions.questions.length)]
console.log(randomObject)
res.set('Content-Type', 'text/html');
res.status(200).send("<h1>Hello GFG Learner!</h1>");
})
app.listen(PORT, (error) =>{
console.log(`Server is Successfully Running, and App is listening on port ${PORT}`)
})

How to call ws WebSocket and wait for response in Express.js?

I have setup Nodejs to serve an HttpServer using ExpressJs. I also need to use ws WebSocket in order to connect to my device for fetching data.
My attempt is now this.
import express from 'express';
import cors from 'cors';
import http from 'http';
import { WebSocketServer } from 'ws';
const app = express();
app.use(cors());
//initialize a simple http server
const httpServer = http.createServer(app);
const wsServer = new WebSocketServer({ port: 7777});
wsServer.on('connection', function connection(ws, req) {
app.get('/', (req, res) => {
ws.send('{"msg":"getdata"}');
ws.on('message', function message(data) {
data = JSON.parse(data);
res.json(data);
});
});
//start our server
httpServer.listen(7778, () => {
console.log(`Server started on port ${httpServer.address().port} :)`);
});
});
The problem is that when the API is called more than once. An error code: 'ERR_HTTP_HEADERS_SENT' is thrown. I assume it is because the ws.on('message') is executed multiple times. So, I am trying to find a way to remove the listener but to no avail.
Is there any better way to do this? I just want to have a webserver that calls to another websocket in order to get data from a device.
For your code example to work, message on websocket must be sent after the / request is made. Because, before that, on message handler is not registered. Also, once handling the first request successfully, you cannot send a websocket message again. Because, when you do that, the res in the message handler is already completed. So, you will get ERR_HTTP_HEADERS_SENT. Thus proved :-)
So, your API calls must be like in the following pattern
/ Call #1
Websocket message #1
/ Call #2
Websocket message #2
If you do so, you will not get the ERR_HTTP_HEADERS_SENT error. Because, res is send once for every / request.
this will solve your error code: 'ERR_HTTP_HEADERS_SENT'
wsServer.on('connection', function connection(ws, req) {
app.get('/', (req, res) => {
//first This
ws.on('message', function message(data) {
data = JSON.parse(data);
res.json(data);
});
//then use this
ws.send('{"msg":"getdata"}');
});
//start our server
httpServer.listen(7778, () => {
console.log(`Server started on port ${httpServer.address().port} :)`);
});
});
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var timeout = require('connect-timeout');
var uuid = require('uuidv4');
var _ = require('lodash');
app.use(timeout('10s'));
app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html');
});
let responses = []
io.on('connection', (socket) => {
socket.on('res', (e) => {
var obj = _.find(responses, r => r.id === e.id);
obj.res.send(e)
_.remove(responses, r => r.id === e.id);
})
})
app.get('/endpoint', (req, res) => {
const id = uuid()
io.emit('req', { id, ip: req.ip, header: req.headers, method: req.method });
responses.push({ id, res })
});
http.listen(3000);
If you want over multiple instance, you can use redis pub sub.

Listening for connections with socket.io not working

I'm using this code for my backend:
const express = require('express');
const app = express();
const socketIo = require("socket.io");
const io = socketIo(http);
io.on("connection", socket => {
console.log("New client connected");
socket.on("disconnect", () => console.log("Client disconnected"));
});
http.listen(3000, () => {
console.log('listening on *:3000');
});
When I run it, it outputs the message confirming it is listening. However, on a connection it does not send any messages to the console. I'm trying to listen for connections to a React app. I have tried using other code snippets for the connection function that also claim to work as I expected, however none that I have tried have worked, including the code in the official tutorial for socket.io.
Please can anyone help?
const express = require('express')
const app = express()
const PORT = 5000
// Get to http://localhost:5000
app.get("/", (request, response) => {
// Send back some data to the client
response.send("Hello world")
})
// Post to http://localhost:5000/getRandom
app.post("/getRandom", (req, res) => {
res.send(Math.random())
})
app.listen(PORT, () => console.log(`Server running on PORT ${PORT}`))
Instead of calling the parameters request and response, people use the short form of req and res
Now start this script and go to http://localhost:5000 and you will see "Hello world" in the HTML body. That's express, simple yet powerful :)

Trouble getting my node.js server to listen with

I am learning node.js and I am trying to figure out how I can get my program to listen at a specific port, but I just keep getting error messages. Is there any easier way I could be doing this, or what do I need to change in my code to allow this to work?
const http = require('http');
const port = 3000
const requestHandler = (request, response) => {
console.log(request.url)
response.end('server is listening!')
}
const server = http.creatServer(requestHandler)
server.listen(port, (err) => ) {
console.log('server is listening on ${port}')
}
I think you should try something like the following to get started.
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.write('Hello World!');
res.end();
}).listen(8080);
Or in your case, I think that the following changes will work:
const http = require('http');
const port = 3000
const requestHandler = (request, response) => {
console.log(request.url)
response.end('server is listening!')
}
const server = http.createServer(requestHandler)
server.listen(port, (err) => {
console.log('server is listening on ${port}')
})
It seems you had a syntax error as well as a typo in your code.

How to acces node server outside local network?

im writing a webserver in nodeJs as seen in the following code. I got the server working but sadly i cant acces the website outside my network (localhost). How can i do this?
var connect = require('connect');
var serveStatic = require('serve-static');
connect().use(serveStatic(__dirname)).listen(80, function(){
console.log('Server running on 80...');
});
I also used this method to check if the other method was the problem.
var http = require('http');
var fs = require('fs');
http.createServer(function (req, res){
fs.readFile('Index.html', function (err, data) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(data);
res.end();
})
}).listen(80);
Have you tried binding the port externally ?
connect().use(serveStatic(__dirname)).listen({
host: '0.0.0.0',
port: 80
}, function(){
console.log('Server running on 80...');
});

Categories

Resources