Node.js: cannot get json object on localhost - javascript

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());
})

Related

create a web server for local html using node

I'm tring to create a simple web server to run my local html file, and now I can get a server running on localhost using code below
var http = require('http');
var fs = require('fs');
var index = fs.readFileSync('index.html', 'utf8');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'html'});
res.end(index);
}).listen(3000);
But there is a problem that every time I changed my html file, the web page on localhost is still the old one, I need to restart the server to make the changes visible.
I want to improve that and I tried to use koa or express, like code below
const express = require("express");
const app = express();
app.listen(3000, () => {
console.log("Application started and Listening on port 3000");
});
app.get("/", (req, res) => {
res.sendFile("test.html");
});
And I found that express can serve real-time html files, I don't need to restart serve when files change.
How can I use http moudle to achieve that?
Currently you read the file when the program starts up. Then each time you get a request you serve up the data from the variable.
Move that code inside the callback function that runs when you get a request, then it will be updated each time a request comes in.
http.createServer(function (req, res) {
var index = fs.readFileSync('index.html', 'utf8');
res.writeHead(200, {'Content-Type': 'html'});
res.end(index);
}).listen(3000);
You could avoid reading the file on each request by having the variable outside the function (as in your original code) and watching the file for changes (and updating the variable in response).
That said, using Express and its static module will provide benefits with caching and I'd recommend it over rolling your own.
You can use nodemon.
npm install -g nodemon
nodemon server.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.

ngrok Cannot GET / local server up and running

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.

node.js http opening static textfiles in browser

If i have a httpserver in node.js that is serving a website on port 3000.
var httpserver = http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
app.get('/', function(req, res) {
res.render('index.html');
});
I need to access a txt file located at /public/
If i for example do localhost:3000/other_site.html, if this other_site.html is in /public/ it opens it, but if the file is txt it doesn't open it.
Is there a solution to this without having to install http-request, connect or other npm modules?
Regards,
Can you use express? If yes,
app.use(express.static(__dirname + '/public'))
makes the trick.
If not, try searching the archives :) Using node.js as a simple web server
What error you are getting ?
if you experiencing browser error, try sending response header and set Content Type text/html and retry
Example code
fs.readFile('myfile.txt', function(error, file) {
response.writeHead(200, {'content-type':'text/html'});
response.end();
});

Running deployd and angular.js app on the same server

I'm trying to run a deployd API on the same server as my AngularJS app, but deployd seems to be conflicting with the app routing.
My deployd server is listening on port 5000 and looks like this:
var deployd = require('deployd');
var server = deployd({
port: process.env.PORT || 5000,
env: 'production',
db: {
host: 'localhost',
port: 27017,
name: 'deployd',
credentials: {
username: 'myUsername',
password: 'myPassword'
}
}
});
server.listen();
server.on('listening', function() {
console.log("Server is listening");
});
server.on('error', function(err) {
console.error(err);
process.nextTick(function() { // Give the server a chance to return an error
process.exit();
});
});
My node server for the AngularJS app is listening on port 3000 and looks like this:
var express = require('express');
var app = express();
app.use(express.static(__dirname + '/public'));
app.listen(process.env.PORT || 3000);
The app loads fine, although it is not hitting the API as expected when making a call like this:
$http.get('localhost:5000/foo')
or this:
$http.get('http://my.public.ip.address:5000/foo')
And my page routing (in HTML5 mode, with no # in the URL) is getting hijacked by deployd -- so a URL routed by AngularJS for '/foo' is hitting the API and returning "Cannot GET /foo".
This is all happening on a server that is also running Apache, but that is configured to forward requests for my domain to port 3000 using something like this:
NameVirtualHost *:80
<VirtualHost *:80>
ServerAdmin webmaster#localhost
ServerName my.domain.com
ProxyPreserveHost on
ProxyPass / http://localhost:3000/
<Location />
Order allow,deny
Allow from all
</Location>
</VirtualHost>
If I use the # in the URL, like http://my.domain.com/#/foo that will return the page template dictated by the AngularJS router, but it is missing data because the API is not being hit on port 5000.
Any help would be greatly appreciated.
Turns out this was a problem with my Express server.js code and had nothing to do with Deployd. I kept seeing the Cannot GET /foo message and just assuming Deployd was trying to fetch a resource, but in fact Express was not loading index.html (which loads AngularJS and my routing code), because it was just trying to load a static file called foo instead.
Here is my fixed server.js:
var express = require('express');
var app = express();
app.use(express.static(__dirname + '/public'));
app.use(function(req, res) {
res.sendfile(__dirname + '/public/index.html');
});
app.listen(process.env.PORT || 3000);
Now, if the static file foo does not exist, it loads index.html and allows my AngularJS router to take the wheel.
have you checked that from a browser that port 3000 as well as 5000 is reachable?
Because you are using proxy pass it makes me think that those ports aren't open. And because angular is run client side, it will never be able to connect to the api if the 5000 port is closed.

Categories

Resources