I have a simple server on node.js running on GCE but I cannot reach the server externally. I'm not sure what is wrong as there is not much indications. Here is my code:
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var fs = require('fs');
app.use(function(req, res, next){
console.log('Request Type:', req.method);
console.log('Request query:', req.query);
next();
});
app.use(bodyParser.urlencoded({ // to support URL-encoded bodies
extended: true
}));
const PORT = 8080;
app.get("/getVideo", function (req, res){
fs.readFile('./index.html', function (err, html){
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(html);
res.end();
})
});
app.listen(PORT, '0.0.0.0');
I can ping the external ip exposed by GCE, but i just cannot reach it. Is there any other setup i need this to work? Or is the code incorrect?
I solved it from Hiren's comment. To go further, I've actually did what he said before, but the thing that did it was the tags. If you set something random, it would not work as it needs to match some other tags. But I left it empty just to test, and it applied it to all instances, and worked.
Related
I am trying to learn middleware in express js. Could anyone help where I am missing? Here is my code
var express = require('express');
var bodyParser = require('body-parser');
var path = require('path');
var app = express();
app.use("/", function(req, res, next){
console.log("this is my second output");
next();
});
app.get('/', function(req,res){
console.log("this is my first output");
//res.send('Hello World');
});
app.listen(3000, function(){
console.log('Server started on port 3000...');
})
I am getting Server started on port 3000.. when I run on cmd and getting "page is not working" on localhost:3000
Edited
I got
Server started on port 3000...
this is my second output
this is my first output
this is my second output
this is my first output
this is my second output
this is my first output
this is my second output
this is my first output
this is my second output
this is my first output
this is my second output
this is my first output
this is my second output
this is my first output
after some time. But localhost:3000 is still not working
The reason you get the "page is not working" message is because your application does not respond to any request it receives.
You'll need to uncomment that res.send('Hello World'); in app.get('/', ...). After that your code works perfectly fine.
Note, however, that in the structure of your code, your middleware app.use(...) is called before you get to the main logic for the route (app.get(...)), contrary to what's indicated by your console.log calls.
var express = require('express');
var bodyParser = require('body-parser');
var path = require('path');
var app = express();
// use this middleware to pass all the requests
app.use("/", function(req, res, next){
console.log("this is my second output");
// move to next middleware
next();
});
//handle all the get requests to localhost:3000 url
app.get('/', function(req,res){
console.log("this is my first output");
// send the response
res.send('Hello World');
// or you can send the response like this
// res.json(JSON.stringify({"success":"true"}));
});
app.listen(3000, function(){
console.log('Server started on port 3000...');
})
send a get request to http://localhost:3000
Mainly, Middlewares execution consists of two things: ->
next()
app.use()
const express = require('express');
const app = express();
const hola = function(req, res, next) {
console.log("are you okay?");
next();
console.log("Yes I'm okay....");
}
app.use(hola)
app.get('/',(req, res) => {
res.send('HEY SUDEEPA WELCOME TO OUR SERVER !!!
})
app.listen(3000,() => {
console.log('Server started at port 3000!!!! ');
})
In the above code if we do not mention the next() method in hola function then after clicking localhost:3000 our will got crashed because it is not getting it's next middleware which is our app.get. So, if we are not mentioning next() then it could be our one of reason for not getting executed Middlewares.
I am new to nodejs/express and have followed a blog article "Build Node.js RESTful APIs in 10 Minutes". It provided detailed steps to create simple REST apis. After finishing every code mentioned in the article, the app have not been working properly, it would just return
{
"url": "/transactions not found"
}
I found that the culprit was in the last part of the article, which told me to add this line to server.js:
Having done all these, what happens if we entered a wrong route? say
you entered 'http://localhost:3000/task', It responds with a message
“Cannot GET /task”. Let’s add express middleware which could be used
to return more interactive messages.
app.use(function(req, res) {
res.status(404).send({url: req.originalUrl + ' not found'})
});
It seems to hardcode a HTTP status code of 404 no matter what does my api returns. After removing this line, the app return meaningful response.
Here is my server.js:
var express = require('express'),
app = express(),
port = process.env.PORT || 3000,
mongoose = require('mongoose'),
Transaction = require('./api/models/transactionModel'), //created model loading here
bodyParser = require('body-parser');
// mongoose instance connection url connection
mongoose.Promise = global.Promise;
mongoose.connect('mongodb://localhost/transactionDb');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(function(req, res) {
res.status(404).send({url: req.originalUrl + ' not found'})
});
var routes = require('./api/routes/transactionRoutes'); //importing route
routes(app); //register the route
app.listen(port);
console.log('Transaction List RESTful API server started on: ' + port);
And the controller:
'use strict';
var mongoose = require('mongoose'),
Transaction = mongoose.model('Transactions');
exports.list_all_transactions = function (req, res) {
Transaction.find({}, function (err, transaction) {
if (err)
res.send(err);
res.json(transaction);
});
};
exports.create_a_transaction = function (req, res) {
var new_transaction = new Transaction(req.body);
new_transaction.save(function (err, transaction) {
if (err)
res.send('Error creating a new transaction!');
res.json(transaction);
});
};
it wasn't override your response, just because it returned in the middle before touch your api. The flow of request is running from top to bottom, example in your code above:
[coming request] --> bodyParser --> bodyParser --> 404 handler (returned here) -x-> api (cannot reach).
Just use() 404 middleware to the bottom and everything works fine.
mongoose.Promise = global.Promise;
mongoose.connect('mongodb://localhost/transactionDb');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var routes = require('./api/routes/transactionRoutes'); //importing route
routes(app); //register the route
app.use(function(req, res) {
res.status(404).send({url: req.originalUrl + ' not found'})
});
I suspect your
app.use(function(req, res) {
res.status(404).send({url: req.originalUrl + ' not found'})
});
should be lower: the server is finding that piece of code first, while the actual routes are loaded later.
app.use means that it always executes that code, so it handles every request by sending a 404 error and saying it can't find the URL.
Put that code under all of the other routes (right above app.listen(port)) and it should work!
The body parser body is {}. I've already done research and made sure that my ajax data key is set correctly as well as make sure the middleware is set up correctly as well. Here is my frontend ajax call
$.ajax({
type:"GET",
url:"/api",
data: {course:"MATH-226"},
success: function(data){ alert(data);}
});
And here is my backend server.js file:
'use strict'
const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');
const alg = require('./app/algorithm.js');
const app = express();
app.use('/', express.static(path.join(__dirname, 'public')));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.get('/api', (req, res) => {
console.log(req.body);
alg.create(req.body.course, answer => res.send(answer));
});
let server = app.listen(3000, () => {
let host = server.address().address;
let port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});
You are using a GET request, so it's probably not being sent. If you need to send something, you can attach it as a header or include it in the query string of the url. If you want to send data, I would use a POST request.
Check out this article
How to send data in request body with a GET when using jQuery $.ajax()
I am trying to post using restler and return the response to client but response never returns .Below is code I am using and response is just hanging
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var rest = require('restler');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var port = 3001; // can also get it from process.env.PORT
var router = express.Router();
//this is like interceptor for every route to validate all requests, logging for analytics
router.use(function (req, res, next) {
console.log('route intercepted');
next(); // make sure we go to the next routes and don't stop here
});
router.get('/', function(req, res) {
res.json({ message: "welcome to restful node proxy layer to business processes" });
});
router.route('/someroute').post(function(req, res) {
rest.postJson('http://localhost/api/sg', req.body).on('complete', function(data, response) {
console.log(response);
}
).on('error', function(data, response) {
console.log('error');
});
});
app.use('/api', router); //all routes are prefixed with /api
app.listen(port);
console.log("server is running magic happens from here");
I've got problemas with Backbone.history.start({pushState: true}); when is actived
I use the backbone router 'example/:id':'test' and the browser returns me an error
GET myhost:1337/example/js/views/test.js 404 (Not Found)
I want to rotate with Backbone for example myhost:1337/example/test without the necessity to request nodejs.
si, I dunno why,
Could be my server Nodejs?
Or Could be my code that it's not well written?
Thanks in advance
MY server code is
//var http = require('http');
var path = require('path'),
express = require('express'),
routes = require('./routes/index'),
http = require('http'),
app = require('express')();
app.configure(function(){
//app.set('view options',{layout: false });
app.set('port', process.env.PORT || 1337);
app.use(express.bodyParser()),
app.use(express.static(path.join(__dirname, 'public')));
app.use(app.router); // you need this line so the .get etc. routes are run and if an error within, then the error is parsed to the ned middleware (your error reporter)
app.use(function(err, req, res, next) {
if(!err) return next(); // you also need this line
console.log("error!!!");
res.send("error!!!");
});
});
app.get('*',function(req,res){
res.setHeader('content-type', 'text/javascript');
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
res.redirect('http://localhost:1337#'+req.url);
});
http.createServer(app).listen(app.get('port'), function () {
console.log("Express server listening on port " + app.get('port'));
});
This is something with your server. I'm willing to bet you didn't hold the shift key down when you typed out your route, so you have something like this in your server
app.get('example?:id':'test', function() {});
When you should have:
app.get('example/:id':'test', function() {});
This block:
app.post('/addPlace?:?',routes.addPlace);
app.get('/searchPlace?:q',routes.searchPlace);
app.post('/showPlace',routes.showPlace);
app.get('/showPlaceById?:id',routes.showPlaceById)
app.post('/deletePlace?:?',routes.deletePlace);
See the ?'s everywhere? This should really be:
app.post('/addPlace',routes.addPlace);
app.get('/searchPlace/:q',routes.searchPlace);
app.post('/showPlace',routes.showPlace);
app.get('/showPlaceById/:id',routes.showPlaceById)
app.post('/deletePlace',routes.deletePlace);
If you change that, /showPlaceById/:id will return what you expect.