ngrok Cannot GET / local server up and running - javascript

I'm trying to follow Crowdbotics' Messenger bot tutorial, however. I did exactly as he mentioned but i am getting this.
My folder:
Okay so, first of all i run node index.js and get the following:
Right after that. We initialize our ngrok server by ngrok http 5000 and get the following:
But on EVERY http request i get the classic Cannot GET /.
On the hindsight, my index.js only contain:
const express = require("express");
const bodyParser = require("body-parser");
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.listen(5000, () => console.log('Webhook server is listening, port 5000'));
I can't really point out what i am doing wrong, your help is truly appreciated.

Based on your express js code, I think you haven't define the routes to '/'
add this before the app.listen on the index.js file
app.get('/', (req, res) => res.send('Hello World!'))

Your index.js has started a server that listens and respond to the HTTP protocol - but it does not "serve files" the same way a web server such as Apache does.
As #Yana notes, you need to explicitly set a route to do something, such as send a text response back.
If you want the favicon.ico file to be sent when requested, then you need to setup a static route for that as part of your index.js code.

Related

Javascript files not loading when hosting a website on digital ocean

I've built a web app with an express backend and using the ejs view engine.
When I run it on my computer it works fine but I'm trying to host in on digitalocean. I cloned it to the droplet(Ubuntu 22.10 x64) and served it on port 80. When I visited it in the browser at 46.101.145.210:80, I got these errors.
GET https://46.101.145.210/javascripts/cookieHandler.js net::ERR_CONNECTION_REFUSED
GET https://46.101.145.210/javascripts/domain.js net::ERR_CONNECTION_REFUSED
Here's my file structure,
Here's the code in index.js.
const express = require("express");
const app = express();
const fs = require("fs");
const path = require("path")
const assert = require("assert");
const PORT = 80
app.use(express.json());
app.use(express.urlencoded({extended: true}));
app.use(express.static('public'));
app.set("view engine", "ejs")
app.listen(PORT, () => {
console.log("Server running on port " + PORT.toString());
});
const domains = ... // Not important
app.get("/", (req, res) => {
res.render("index")
//res.redirect("/domain")
})
app.get("/domain", (req, res) => {
res.render("domain", {domains: domains})
})
I've tinkered with the firewall config and the express.static to see if it would make a difference. I couldn't figure anything out though.
Update: I've checked the requests out a bit. They are https requests. When I use postman and change the request to be http it works.
I solved it by adding a valid ssl certificate.
Looking your file structure and the code, I can say, you must define the full path of the public directory using
express.static(__dirname+'/public')
Or can be like
const path = require('path');
// .... your code ...
app.use(express.static( path.join(__dirname, 'public') ));
with this you are forcing to define where the public directory is on the ubuntu, and validate you are accessing your files
Hope you can solve with this
Update: checking carefully, I can see that your are trying to request using https, but your code is working on port 80 (http), so you said, on postman worked without https because of the port. If you want to have working your code with port 443 (https), you must have a certificate (with domain but not required), then try with https://46.101.145.210/javascripts/cookieHandler.js otherwhise try http://46.101.145.210/javascripts/cookieHandler.js.

Express server routes not being hit. Browser Error 'No Data Received ERR_EMPTY_RESPONSE'

I'm having an issue with my express server with an email service I was attempting to set up. After troubleshooting I decided to boil it down and attempt see if the issue would replicate with a simple 'hello world' example, which it did. No routes will be work correctly each request, whether done by a js frontend, postman, or just in a chrome browser will work. Each request will just 'spin' until it returns a 'No Data Received ERR_EMPTY_RESPONSE' error.
I've tried reinstalling the express dependency, reinstalling node itself, different browsers. The code is attached, any help would be appreciated.
const express = require('express');
const cors = require('cors');
const app = express();
let port = 3000;
app.use(cors);
app.get('/testroute', (req, res) => {
console.log('route hit');
res.send('test success');
});
app.listen(port, () => {
console.log('server started on port: ' + port);
});
Change this:
app.use(cors);
to this:
app.use(cors());
Your server was hanging because you were passing cors as middleware. But, cors by itself is not middleware. When Express called it, it never sent a response or called next() to continue routing, so therefore the client was just left hanging forever waiting for a response. Instead, the cors library is designed to that you call it as in cors() to get back a middleware function that you then pass to Express.
This is fully documented in the cors library documentation.

Heroku custom DNS API route issue in Node.js

I have a custom domain set up in Heroku which works fine.
I can access my site using both my app name and custom domain.
I can access a route using my standard Heroku URL, but not using the custom domain.
For example:
Works:
https://{myappname}.herokuapp.com
https://{myappname}.herokuapp.com/callback
https://{customdomain}.com
Does not work:
https://{customdomain}.com/callback
Server config:
const express = require("express");
const path = require("path");;
const callback = require("./callback");
const app = express();
// Body parser middleware
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
// Serve static assets if in production
if (process.env.NODE_ENV === "production") {
app.use("/callback", callback);
// Set static folder
app.use(express.static("client/build"));
app.get("*", (req, res) => {
res.sendFile(path.resolve(__dirname, "client", "build", "index.html"));
});
}
// Init server/port
const port = process.env.PORT || 5000;
app.listen(port, () => console.log(`Server running on port ${port}`));
I know its too late but I am writing for those who face this issue in the future.
I was also facing this issue and solved through this.
Was Not Working
https://{customdomain}.com/callback
This Worked for me.
https://www.{customdomain}.com/callback
I figured this out, it was pretty simple and I feel stupid, however I will answer this here in case anyone ever has the same issue.
Problem:
I had a React route/component called Callback. This React component was calling a Node.js route also called Callback, which processes information then redirects to a new React route/component.
Simple fix was to change my React route/component to callbackPage, leaving my Node.js route as Callback.
So in summary, I had a webpage URL with the same name as a server API route. when I visited this page, instead of the page being rendered, the API route was run and basically did nothing and timed out. I'm still confused as to why it worked with my app URL but not my custom domain.

Node.js/express.js default routing changes not being seen in ubuntu

EDIT ------------
so I figured out the issue, restarting and reloading nginx didn't have any effect, but if I stoped the nginx instance, then restarted it, any changes I made to the server files took effect. It's great that I figured it out, but could anyone give me some insight into why this is? It's better if I understand why this was happening. Any changes I made to the client side files such as the html files took affect immediately, it was only the server files that I had to stop then restart the nginx instance for it to take affect.
ORIGINAL POST BELOW----------------------
Any changes I make to the server side files of my deployed Node.js app with express.js isn't being seen by ubuntu. Basically, I have a mean app deployed on ubunut, it is a multipage page app, with only one of those pages having partials, so i use my routes.js
to catch the routes and send them to my main.js file to tell express and node which html or ejs file to load.
I made changes to the version on my computer so that all other routes would go to a certain html, it works great. But I pushed my changes to github, then pulled them in my ubuntu instance, and it's not working. All other changes I made to the project during this time that were pushed with it have taken affect. But, it's like ubuntu isn't letting node see any changes to the routes.js file, the code is there, I've even altered it with 'vim' from my terminal, but any changes I make, even ones that should break it, aren't seen by node. And going to an unexpected route displays the 'cannot GET...' page.
I've wracked my brain, but i'm stumped, the code is there and I can change it, I've altered html pages via vim to test it. But both, the routes.js file that handles my routing and my server.js file aren't reflecting my changes, even when I change things that should break it. Any ideas? Let me know if you need anymore info, i've included my files below. Also, I use nodemon so that it restarts automatically anytime changes are made
SERVER.JS FILE -------------------------------
var express = require('express'),
app = express(),
path = require('path'),
bodyParser = require('body-parser')
app.use(bodyParser.urlencoded({extended: true}))
app.use(bodyParser.json())
app.use(express.static(path.join(__dirname, './client')))
app.use(express.static(path.join(__dirname, './client/views')))
app.use(express.static(path.join(__dirname, './bower_components')))
app.set('views', path.join(__dirname, './client'));
app.set('view engine', 'ejs');
require('./server/config/routes.js')(app)
var port = 8000
app.listen(port, function(){
console.log('Server on port: ' + port)
})
ROUTES.JS FILE -----------------------------
var Main = require('../serverControllers/main.js')
module.exports = function(app){
app.get('/', Main.main)
app.get('/contact', Main.contact)
app.get('/algorithms', Main.algorithms)
app.get('/projects', Main.projects)
app.get('*', Main.other)
app.use(Main.other)
}
MAIN.JS FILE ----------------------
module.exports = {
main: function(req, res){
res.render('index')
},
contact: function(req, res){
res.render('contact')
},
algorithms: function(req, res){
res.render('algorithms')
},
projects: function(req, res){
res.render('projects')
},
other: function(req, res){
res.render('default')
},
}

Node.js: cannot get json object on localhost

I have an android app that is going to send a json to my server where I will have a node.js express app. Meanwhile, I want to test it on my localhost.
On my android code I send the json to:
new HttpAsyncTask().execute("http://10.0.2.2:8080/ReceiveJson");
This code is triggered by a button and is working fine.
Then in my app.js file I have the following code:
var express = require('express')
, http = require('http');
var app = express();
app.set('port', process.env.PORT || 8080);
app.get('/ReceiveJson', function(req, res) {
console.log(req.body);
res.send(req.body);
res.json(req.body);
res.send("ok");
});
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
In my terminal I run node app.js and I get just the answer "Express server is listening on port 8080". Nothing else.
When I go to my browser and put
http://localhost:8080/ReceiveJson
I get "{}" as an answer.
In my terminal I get the same answer.
What do I have to do to receive the json?
Thanks
That's because you are responding with the req.body:
res.send(req.body);
The code below it never gets called because you have already responded:
res.json(req.body);
res.send("ok");
Because you are using a web browser, there is nothing being sent in the body because it is a get request and there will be nothing in the body for a get request, therefore you get an empty json object, hence {}.
If you change your code to:
app.get('/ReceiveJson', function(req, res) {
res.send("ok");
});
Then when you browse there in your browser you will get the response 'ok'
If you are looking to post or put to your express server then you need to use either app.post or app.put. I noticed that you are trying to send JSON with an Android device for an app you have already written. I would highly recommend using Fiddler or something to test with, just make sure that when you send JSON to your express app you are using the header:
Content-Type: application/json
EDIT:
Your JSON might not be working because you aren't using the body parser. Try inserting this in your code before app.listen
app.configure(function(){
app.use(express.bodyParser());
})

Categories

Resources