2014-11-08 18 views
5

Im bir metin bazı metin gönderme node.js içinde xhr isteği ile gönderin:Access veri XMLHttpRequest tarafından ekspres sunucuyu node.js için

:

var text = document.getElementById("textBox").value; 
    console.log(text); 
    var xmlhttp; 
    if (window.XMLHttpRequest) 
    {// code for IE7+, Firefox, Chrome, Opera, Safari 
    xmlhttp=new XMLHttpRequest(); 
    } 
    else 
    {// code for IE6, IE5 
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); 
    } 
    xmlhttp.onreadystatechange=function() 
    { 
     if (xmlhttp.readyState==4 || xmlhttp.status==200) 
     { 
     document.getElementById("textBox").value =xmlhttp.responseText; 
     } 
    } 
    xmlhttp.open("POST","http://127.0.0.1:3000/",true); 
    xmlhttp.send(text); 

Sorum benim sunucusunda erişmek için nasıl

var http = require("http"); 
var url = require("url"); 
var qs = require('querystring'); 
var path = require('path'); 
var bodyParser = require('body-parser'); 
var express = require('express'); 

var app = express(); 
// start endle req\res 
app.use(bodyParser.json()); 
app.use(bodyParser.urlencoded({ extended: false })); 
app.post('/', function(req,res){ 
    console.log("request method :" + req.method); 
    res.end("OK"); 
}); 

// listen at local host:3000 
var server = app.listen(3000, function() { 
    console.log('Listening on port %d', server.address().port); 
}); 

Dize, istek yükü olarak görünür ve jQuery'yi kullanmak istemiyorum.

cevap

-2

Sen req.body aracılığıyla istek gövdesini okuyabilir:

app.post('/', function(req,res){ 
    console.log("request method :" + req.method); 
    console.log("request body :" + req.body); 
    res.end("OK"); 
}); 
0

bodyParser bir isteğin gövdesini kabul nasıl olduğundan, için 'application/json' için istek başlığı "Content-Type" belirlemek zorunda düzgün çalışma isteğiniz. Bu başarmak için çok basittir; Basit bir xmlhttp.setRequestHeader('Content-Type', 'application/json') hile yapacaktır.

+0

Sana küçük bir hata yaptığımı düşünüyorum: yerine 'xmlhttp.setRequestHeader ('Content-Type', 'application.json')' o 'xmlhttp.setRequestHeader ('Content-Type', 'application/olmalıdır arasında json ')' –