I am having a real hard time standing up bidirectional data transfer from a html page to my node.js application and then back to the html page.
I\'m pretty sure I\'m
Your code is perfectly fine, but you're almost certainly running into a cross-domain AJAX request issue. You might be opening this HTML file on the local filesystem and making requests that way, which is what is causing this problem.
To fix it, add app.use(express.static('public'));
like so:
var express = require('/usr/lib/node_modules/express');
var app = express();
app.use(function(err, req, res, next){
console.error(err.stack);
res.send(500, 'Something broke!');
});
app.use(express.bodyParser());
app.use(express.static('public'));
app.post('/namegame', function(req, res)
{
console.log('Got request name: ' + req.body.name);
setTimeout(function()
{
var newName = "New Name-O";
res.send({name: newName});
}, 2000);
}
);
app.listen(8088, function() { console.log("Server is up and running"); });
and then place your html file in the 'public' folder. Once you launch your server, you can visit http://127.0.0.1:8088/file.html
and your code will run fine.
In my case adding this to the app.js
works.
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
https://enable-cors.org/server_expressjs.html