const express = require('express');
const https = require('https');
const app = express();
app.get("/" , function(req, res) {
const url = "https://api.openweathermap.org/data/2.5/weather?q=Bhubaneswar&appid=5b1ee8df0720f3eca886c9ca1cb03385&units=metric";
https.get(url, function(request, response){
console.log(response);
});
res.send("Server is up & running");
});
app.listen(5000, function() {
console.log("Server is running at port 5000");
});
[Nodemon app getting crashed][1]
[1]: https://i.stack.imgur.com/rka1M.jpg
When ever am running the nodemon, error is arising as UNABLE_TO_VERIFY_LEAF_SIGNATURE. Even tried several ways provided bu Stack Overflow & GitHub. Still none of them worked out.
Related
I'm probably doing something silly, and putting myself in a situation that I don't need to be in. But my ultimate question is why do I have to have an empty folder in my server in order for my GET requests to work?
Before I start with an example, everything is under a subfolder: http://www.example.org/subfolder1
Here is Server code:
const express = require('express');
const datastore = require('nedb');
const url = require("url");
var path = require('path');
const app = express();
var server = require('http').createServer(app);
var io = require('socket.io')(server,
{
path: '/subfolder1/socket.io',
cors:
{
origin: '*',
methods: ["GET", "POST"],
credentials: true
}
});
const port = 3000;
io.on('connection', socket => {
console.log("Socket connected: " + socket.id);
});
app.get("/subfolder1/getSettings", (req, res, next) => {
res.json({ configuration: conf });
});
app.use(express.json());
app.get("/subfolder1/", function (req, res) {
res.sendFile(path.join(__dirname, 'public', 'index.html'));
});
app.use(express.static(path.join(__dirname, 'public')));
server.listen(port, '0.0.0.0', function(error){
if(error) {
console.log('Server failed to listen: ', error)
} else{
console.log('Server is listening on port: ' + port)
}
});
client code:
const response = await fetch("/subfolder1/getSettings");
const settings = await response.json();
Now, in this example I'm calling getSettings (http://www.example.org/subfolder1/getSettings):
app.get("/subfolder1/getSettings", (req, res, next) => {
res.json({ configuration: conf });
});
No matter what I do, I will forever get a 404 error message unless I create an empty folder called "getSettings" in my folder structure on my server. Once I create the empty folder, the call works! So for now, I've just making empty folders on my server for my get calls. Well now look what happens when the URL is something more complicated, such as the following:
http://www.example.org/subfolder1/team=6/queuedPlayers (Where team can be any integer)
Now I'm stuck and my workaround is broken. Any ideas?
I am getting cross origin headers error despite running cors library, or simply a 404 not found while polling in the console.
The project structure looks like this
My goal is to have the little chat widget on every view. I will include this to the other views as EJS partial.
I am not sure what I going wrong I have tried to run Express on port 5000 and Socket IO on 8080 or 3000, all different combinations have not yielded anything good.
APP.JS looks like this
const { check } = require('express-validator');
const express = require("express");
const session = require("express-session");
const MongoDBStore = require("connect-mongodb-session")(session);
const config = require("config");
const flash = require('express-flash');
const cookieParser = require('cookie-parser');
const nodemailer = require("nodemailer");
const Mailgen = require("mailgen");
const dotenv = require('dotenv');
dotenv.config();
const appController = require("./controllers/appController");
const isAuth = require("./middleware/is-auth");
const connectDB = require("./config/db");
const mongoURI = config.get("mongoURI");
const bodyParser = require('body-parser');
var cors = require('cors') // This should help, but does nothing
const app = express();
const http = require('http').Server(app); // I suspect the mistake is in these lines
const io = require('socket.io')(http,
{
cors: {
origin: "http://localhost:5000", // Does nothing
credentials: true
}})
connectDB();
const store = new MongoDBStore({
uri: mongoURI,
collection: "mySessions",
});
app.use(cors({origin: '*'})) // Also seems not to be working
app.set("view engine", "ejs");
app.use(express.urlencoded({ extended: true }));
//Middleware and Routes
io.sockets.on('connection', function(socket) {
console.log("hello") // never happened
socket.on('username', function(username) {
console.log("hello") // never happened
socket.username = username;
io.emit('is_online', '🔵 <i>' + socket.username + ' join the chat..</i>');
});
socket.on('disconnect', function(username) {
io.emit('is_online', '🔴 <i>' + socket.username + ' left the chat..</i>');
})
socket.on('chat_message', function(message) {
io.emit('chat_message', '<strong>' + socket.username + '</strong>: ' + message);
});
});
app.listen(5000, console.log("App Running on http://localhost:5000"));
And the front end partial EJS looks like this
<ul id="messages"></ul>
<form action="/" method="POST" id="chatForm">
<input id="txt" autocomplete="off" autofocus="on" oninput="isTyping()" placeholder="type your message
here..." /><button>Send</button>
</form>
The rest of the front end page looks like this
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/3.0.4/socket.io.js" integrity="sha512-aMGMvNYu8Ue4G+fHa359jcPb1u+ytAF+P2SCb+PxrjCdO3n3ZTxJ30zuH39rimUggmTwmh2u7wvQsDTHESnmfQ==" crossorigin="anonymous"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<style> etcetc
<%- include ('./partialChatWidget.ejs') %>
And the JS
<Script>
var socket = io.connect('http://localhost:5000', { transport : ['websocket'] } );
$('form').submit(function(e){
e.preventDefault();
socket.emit('chat_message', $('#txt').val());
$('#txt').val('');
return false;
});
socket.on('chat_message', function(msg){
$('#messages').append($('<li>').html(msg));
});
socket.on('is_online', function(username) {
$('#messages').append($('<li>').html(username));
});
var username = prompt('Please tell me your name');
socket.emit('username', username);
</script>
So what is going wrong here, do I need 2 servers on different ports or 2 instances, I always thought socket IO borrows the http server , not the express instance.
Thanks for helping me out. I might add I get the cross origin errors when I try to run on 2 different ports. Else I get 404 not found in the console. The page and the partial and the initial JS(Jquery) run.
After a lot of back and forth....
Just make sure to load the front end link for socket IO right in the head section asap.
And do include this part on the front end
var socket = io.connect('http://localhost:5000', { transport : ['websocket'] } );
Definitely include this on the server side, this cant hurt, unless you want to block some pages from CORS access
app.use(cors({origin: '*'}))
The next 2 steps made it all work.
const app = express();
const http = require('http').Server(app);
const io = require('socket.io')(http,
{
cors: {
origin: "http://localhost:5000 {this is the port of your back end app, not for the socket IO port }",
credentials: true
}})
And finally, indeed, 2 servers.
const server = http.listen(8080, function() {
console.log('listening on *:8080');
});
app.listen(5000, console.log("App Running on http://localhost:5000"));
Took me a while, but now everything is clear once and for all(I hope)
app.use((req,res, next)=>{
res.setHeader('Access-Control-Allow-Origin',"http://localhost:3000");
res.setHeader('Access-Control-Allow-Headers',"*");
res.header('Access-Control-Allow-Credentials', true);
next();
});
use this code
and install the older socket.io version 2.3.0
try this code
`const server = app.listen(PORT,()=>console.log(`listening on port ${PORT}`));
io = require('socket.io').listen(server);
io.on('connection', (socket) => {
console.log('a user connected');
});`
app.route('/ad/apply')
.put(adController.applyAd)
.post(notificationController.addNotification)
Above route won't work, I got error 404 not found if I added in 3rd line like that. How do I do PUT and then POST? if it's both PUT I can just do
app.route('/ad/apply')
.put(adController.applyAd, notificationController.addNotification)
Above route won't work, I got error 404 not found if I added in 3rd line like that.
To reproduce your scenario locally, I tried the following code. It didnt have any specific issues with line alignment.
'use strict';
let http = require('http');
let express = require('express');
let app = express();
let server = http.createServer(app);
const PORT = 8888;
server.listen(PORT, () => {
console.log(`Server is up at ${PORT}`);
app.route('/').put((req, res) => {
return res.status(200).send({
msg: 'hello from PUT'
});
}).post((req, res) => {
return res.status(200).send({
msg: 'hello from POST'
});
});
});
May be, 404 is because of some other routes taking precedence over this based on the order of declaration.
I am building a proxy server which is supposed to forward data from an Shoutcast server to the client. Using request or even Node's http module this fails due to missing HTTP header:
{ [Error: Parse Error] bytesParsed: 0, code: 'HPE_INVALID_CONSTANT' }
The URL in question is: http://stream6.jungletrain.net:8000
Doing a header request with curl I was able to verify this:
$ curl -I http://stream6.jungletrain.net:8000
curl: (52) Empty reply from server
Yet the stream is working fine as tested with curl stream6.jungletrain.net:8000.
Is there a way to disable the header verification in request or Node's http? This is the code I am testing it on:
var express = require('express');
var request = require('request');
var app = express();
app.get('/', function (req, res) {
request('http://stream6.jungletrain.net:8000').pipe(res);
stream.pipe(res);
});
var server = app.listen(3000, function () {
console.log('Server started')
});
I am aware this can be achieved by rolling an implementation with net, there is also icecast-stack but subjectively seen it only implements half of the Stream interfaces properly.
Using icecast, I was able to get this working both using the on('data') event and by piping it to the Express response:
var express = require('express');
var app = express();
var icecast = require('icecast');
var url = 'http://stream6.jungletrain.net:8000';
app.get('/', function(req, res) {
icecast.get(url, function(icecastRes) {
console.error(icecastRes.headers);
icecastRes.on('metadata', function(metadata) {
var parsed = icecast.parse(metadata);
console.error(parsed);
});
icecastRes.on('data', function(chunk) {
console.log(chunk);
})
});
});
var server = app.listen(3000, function() {
console.log('Server started')
});
Or simply:
app.get('/', function(req, res) {
icecast.get(url).pipe(res);
});
Also of some note:
It appears the icecast package has been superseded by https://www.npmjs.com/package/icy
I'm a beginner programmer and pretty new to Node.js.
I managed to setup a single static page by using AWS EC2 and Heroku, but I need help making other subpages. ie. mysite/blog or mysite/archive.
I started out with a simple web.js file I got from a sample node app which was:
var express = require('express');
var app = express();
app.use(express.logger());
app.get('/', function(request, response) {
response.send('Hello World!');
});
var port = process.env.PORT || 5000;
app.listen(port, function() {
console.log("Listening on " + port);
All that said was Hello World so I created index.html and changed web.js to this.
var express = require('express');
var fs = require('fs');
var htmlfile = "index.html";
var app = express(express.logger());
app.get('/', function(request, response) {
var html = fs.readFileSync(htmlfile).toString();
response.send(html);
});
var port = process.env.PORT || 8080;
app.listen(port, function() {
console.log("Listening on " + port);
Now that serves index.html instead, but how do I get /blog or /archive to work?
You can add other routes to your code to handle specific URL formats. Make sure the more specific URLs are listed before the general route (/ or *)
// Handle request for blog
app.get('/blog', function(req, res){
res.send('A list of blog posts should go here');
});
// Handle request for archive
app.get('/archive', function(req, res){
res.send('Archive content should go here');
});
// Route for everything else.
app.get('*', function(req, res){
res.send('Hello World');
});
I've got a more lengthy explanation about this here: http://hectorcorrea.com/#/blog/introduction-to-node-js/51