Peter Pansky Peter Pansky - 5 months ago 14
Node.js Question

Can't get response from Node.js

I'am trying to calculate the BMI with JavaScript (Clienside) and Node.js (Serverside).

If I call the Node URL and pass Parameters I get a response,
but if I call the Node URL with an

xhr
I dont get a
responseText
.

I get statuscode 200 but not the
responseText
.

Where is the problem? Thanks for your help!

Node.js

var express = require('express');
var bodyParser = require('body-parser');
var app = express();

app.get('/bmi', function(req, res){
var bmi = req.query.weight / (req.query.height * req.query.height);
var msg = 'Hallo '+req.query.name+', deine BMI ist ' + bmi;
res.send(msg);
console.log(msg);
}).listen(80);


Javascript

function bmi(){
var response;
var name = document.getElementById("name-input").value;
var weight = document.getElementById("weight-input").value;
var height = document.getElementById("height-input").value;

var xhr = new XMLHttpRequest();

xhr.onreadystatechange = function(){
//console.log(xhr.readyState);
if(xhr.readyState === 4 && xhr.status === 200){
response = xhr.responseText;
document.getElementById("response").innerText = response;
}
//console.log(xhr.responseText);
};

xhr.open("GET", "http://localhost/bmi?name="+name+"&height="+height+"&weight="+weight, true);
xhr.send();
}

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

This header fixes my Problem =)

Comments