2016-10-10 317 views
-1

因此,我正在制作一个应用程序,允许我在客户端输入一些数据,无论是在同一网络中运行的电话还是其他桌面。阅读请求主体Node.js服务器

我有一个Node.js服务器,它回答我的请求,但我实际上无法在服务器端“读取”它们。

这是我的服务器代码

var http = require("http"); 

var parseString = require('xml2js').parseString; 

var express = require('express') 
var app = express(); 
var port = process.env.PORT || 8081; 


var request = require('request'); 


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


// start the server 
app.listen(port); 
console.log('Server started! At http://localhost:' + port); 


// routes will go here 
app.use('/static', express.static('.')); 

var bodyParser = require('body-parser'); 
app.use('/browse', bodyParser.json()); // support json encoded bodies 
app.use('/browse', bodyParser.urlencoded({ extended: true })); // support encoded bodies 


app.get('/', function(req, res, next) { 
    // Handle the get for this route 
}); 

app.post('/', function(req, res, next) { 
// Handle the post for this route 
}); 


// POST http://localhost:8081/browse 
app.get('/browse', function(req, res) { 
    var browseRequest = req.body.browseRequest; 
    console.dir("browseRequest: "); 
    console.dir(browseRequest); 

    res.send(JSON.stringify("response")); 

}); 

(我有多余的东西在这里?)

这是我使用我的html页面

// Create the XHR object. 
    function createCORSRequest(method, url) { 

     var xhr = new XMLHttpRequest(); 
     if ("withCredentials" in xhr) { 
     // XHR for Chrome/Firefox/Opera/Safari. 
     xhr.open(method, url, true); 
     } else if (typeof XDomainRequest != "undefined") { 
     // XDomainRequest for IE. 
     xhr = new XDomainRequest(); 
     xhr.open(method, url); 
     } else { 
     // CORS not supported. 
     xhr = null; 
     } 
     return xhr; 
    } 


    // Make the actual CORS request. 
    function makeCorsRequest() { 
     // This is a sample server that supports CORS. 
     var url = "http://192.168.0.100:8081/browse" 
     var xhr = createCORSRequest('GET', url); 
     if (!xhr) { 
     alert('CORS not supported'); 
     return; 
     } 

     //xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8"); 

      var req = { "browseRequest": { 
       "name": "Aaron", 
       "type": "Consumer", 
       "age": 21 

      }}; 
      xhr.send(JSON.stringify(req)); 

    } 

部分我得到由我的客户端上的服务器发送的字符串,但我无法访问服务器中的browserequest,因为req.body即将空白。

我在这里错过了什么? 谢谢!

+0

你没有告诉服务器你发送了什么。 (注释部分) –

+0

我之前评论过它,因为我收到了CORS错误。 即使没有注释,我仍然有空身体。 任何提示? – seugnimod

回答

-1

GET参数(主要)没有身体。 (Read this

您可以req.paramsreq.query

获取参数,但在你的Ajax调用,你必须queryString您的数据。

+0

可以通过GET请求发送JSON正文,并且body-parser确实支持这一点。 –

+0

您可以给我一个工作示例,让一个Ajax调用一个json主体...我不确定浏览器允许在GET请求中传递主体...(我知道这可能与CURL) –

+0

感谢您的输入史蒂夫。我还想看看@凯文的例子。 – seugnimod