简体   繁体   中英

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

Well, are you sure your localhost:80 is not used? I've tried with 8080 and it works (i edit the js request aswell)

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 fixed my Problem =)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM