For my first experience using Node, I have hosted a Nodejs server on Openshift that I am hoping to use for an Android application server soon. Currently, I'm trying to get a simple express app that will respond to an HTTP POST request. Here is the code for this server; I've made it as simple as possible, and it responds to GET requests just fine, but the POST callback never seems to execute:
#!/bin/env node
var http = require('http');
var bodyParser = require('body-parser');
var express = require('express');
var app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.post('/', function (req, res) {
res.end("Post successful.");
});
app.get('/', function (req, res) {
res.end("App listening on port: " + process.env.OPENSHIFT_NODEJS_PORT);
});
http.createServer(app).listen(process.env.OPENSHIFT_NODEJS_PORT,
process.env.OPENSHIFT_NODEJS_IP, function() {
console.log("Server started on %s.", Date(Date.now()));
});
Here is the Node script that I have been using to test the response. I do not believe it is the issue, because I have also tried POSTing in Java and using an HTML form, but neither of those seem to work either:
var http = require('http');
var data = JSON.stringify({
'message' : 'hello'
});
var options = {
host: 'xx-xx.rhcloud.com',
port: '8080',
path: '/',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': data.length
}
};
var request = http.request(options, function(res) {
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log('Response: ' + chunk);
});
res.on('end', function(err) {
console.log("Post successful");
});
});
request.write(data);
request.end();
I can get the callback to execute when running the server locally, but only if I hard-code the port and the IP at that point. Once I start the server, it responds to the GET request with the port, which I assumed would always be 8080, but even hard-coding 8080 for the port on the host doesn't resolve the issue. Still, I'm assuming it's an issue with the port because my posting script and browser both hang up when I try to send the request, instead of throwing a connection error. Granted, I'm a complete noob and I could easily be overlooking a simple but critical element. Thanks in advance.
This probably speaks to my inexperience with web technology in general, but I discovered the problem; when trying to POST to a particular port, the server is unresponsive. If, however, I remove the port declaration altogether from my POSTing script, then it works correctly. Could somebody maybe explain why that is?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With