无法接收来自Post请求的Node.js响应(不使用Express)

时间:2018-10-13 02:18:38

标签: node.js http post xmlhttprequest

我的服务器很好地收到了我的发帖请求,但是服务器没有响应(也没有通过Web检查器的响应)。我已经为跨源和所有内容设置了标题。这是我的nodejs服务器代码。有问题的代码在底部。

http.createServer(function (request, response) {

if(request.url === '/action'){
    //console.log("momma I made it");
    let body = '';
    request.on('data', chunk => {
        body += chunk.toString();
    });
    request.on('end', () => {
        var log = JSON.parse(JSON.stringify(parse(body)));
        console.log(log);
        if(log.accT == 'Admin') {
            if(log.account == 'nUser'){
                console.log("this is an new user");
                randnum = random();
                var sql = "INSERT INTO Admin (adminName, adminEmail, adminPassword, adminID) VALUES ('" +log.username+ "', '" +log.email+ "', '" +log.password+ "', '" +randnum+ "')"
                con.query(sql, function (err, result) {
                    if (err) throw err;
                    response.end('new user created, changed response remotely')
                });
            }
            if(log.account == 'eUser'){
                console.log("this is an existing user");

                var sql = "SELECT adminName,adminPassword FROM Admin WHERE adminName = '"+log.username+"'";
                con.query(sql, function (err, result, fields) {
                    if (err) throw err;
                    //var pass = parse(result);
                    if(result.length != 0 && result[0].adminPassword === log.password) response.end('youre in big guy')
                    else response.end('wrong username or password');
                });
            }
        }
        if(log.accT == 'Sponsor') {
            if(log.account == 'nUser'){
                console.log("this is an new user");
                randnum = random();
                var sql = "INSERT INTO Sponsor (adminEmail,sponsorEmail, sponsorName, sponsorPassword, sponsorID) VALUES ('" +log.authEmail+ "','" +log.email+ "', '" +log.username+ "', '" +log.password+ "', '" +randnum+ "')"
                con.query(sql, function (err, result) {
                    if (err) throw err;
                    response.end('new user created, changed response remotely')
                });
            }
            if(log.account == 'eUser'){
                console.log("this is an existing user");

                var sql = "SELECT sponsorName,sponsorPassword FROM Sponsor WHERE sponsorName = '"+log.username+"'";
                con.query(sql, function (err, result, fields) {
                    if (err) throw err;
                    //var pass = parse(result);
                    if(result.length != 0 && result[0].sponsorPassword === log.password) response.end('youre in big guy')
                    else response.end('wrong username or password');
                });
            }
        }
        if(log.accT == 'Driver') {
            if(log.account == 'nUser'){
                console.log("this is an new user");
                randnum = random();
                var sql = "INSERT INTO Driver (sponsorEmail, driverName, driverEmail, driverPassword, driverID) VALUES ('" +log.authEmail+ "','" +log.username+ "','" +log.email+ "', '" +log.password+ "', '" +randnum+ "')"
                con.query(sql, function (err, result) {
                    if (err) throw err;
                    response.end('new user created, changed response remotely')
                });
            }
            if(log.account == 'eUser'){
                console.log("this is an existing user");

                var sql = "SELECT driverName,driverPassword FROM Driver WHERE driverName = '"+log.username+"'";
                con.query(sql, function (err, result, fields) {
                    if (err) throw err;
                    //var pass = parse(result);
                    if(result.length != 0 && result[0].driverPassword === log.password) response.end('youre in big guy')
                    else response.end('wrong username or password buckaroo');
                });
            }
        }
        if(log.action == 'update'){

            //response.write('hello');
        }
        //response.end('ok');
    });
    //response.writeHead(200)
    //fs.createReadStream('server2.html').pipe(response)  // do NOT use fs's sync methods ANYWHERE on production (e.g readFileSync) 
}
if(request.url === '/myaction'){
    response.writeHead(200)
    fs.createReadStream('SignUp.html').pipe(response)  // do NOT use fs's sync methods ANYWHERE on production (e.g readFileSync)  
}
if(request.url === '/myaction2'){
    response.writeHead(200)
    fs.createReadStream('SignIn.html').pipe(response)  // do NOT use fs's sync methods ANYWHERE on production (e.g readFileSync)  
}
if(request.url === '/?action=update'){
    //response.write('hello Isaac');
}
if (request.method == 'POST') {
    console.log("POST");
    var body = '';
    request.on('data', function (data) {
        body += data;
        console.log("Partial body: " + body);
    });
    request.on('end', function () {
        console.log("Body: " + body);
    });
    response.setHeader('Access-Control-Allow-Origin', '*');
    response.setHeader('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
    response.setHeader('Access-Control-Allow-Headers', 'Content-Type');
    response.writeHead(200, {'Content-Type': 'text/html'});
    response.end('post received'); 
}

这是我的html接收代码

var xhttp = new XMLHttpRequest();
xhttp.open("POST", "url not posted because I have no security", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.onreadystatechange = function() {
  if (this.readyState == 4 && this.status == 200) {
    console.log(this.responseText);
  }
};
xhttp.send('action=update');

我的服务器很好地收到了消息。非常感谢您的任何帮助!

2 个答案:

答案 0 :(得分:1)

Nodejs http没有标头方法。您必须使用setHeader方法response.setHeader('Access-Control-Allow-Origin', '*');

答案 1 :(得分:0)

在较早的阶段,我尝试将纯文本发送给HTML的响应时遇到了类似的问题。它不会发送对HTML的响应。所以我所做的就是我将值存储在变量中并赋予了response.end(variable_name);,并且效果很好...

如果有误,请纠正我。