2014-11-08 11 views
5

Im gửi một số văn bản từ một textbox để Node.js Server Express của XMLHttpRequest:Truy cập dữ liệu gửi theo yêu cầu XHR trong Node.js

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

Câu hỏi của tôi là làm thế nào để truy cập vào nó trong máy chủ của tôi:

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

Chuỗi xuất hiện dưới dạng yêu cầu tải trọng và tôi không muốn sử dụng jQuery.

Trả lời

-2

Bạn có thể đọc nội dung yêu cầu qua req.body:

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

Do cách bodyParser chấp nhận cơ thể của một yêu cầu, bạn phải thiết lập các yêu cầu tiêu đề "Content-Type" để 'application/json' cho yêu cầu của bạn hoạt động bình thường. Điều này rất đơn giản để thực hiện; một đơn giản xmlhttp.setRequestHeader('Content-Type', 'application/json') sẽ thực hiện thủ thuật.

+0

Tôi nghĩ bạn đã mắc một lỗi nhỏ: Thay vì 'xmlhttp.setRequestHeader ('Content-Type', 'application.json')' nó phải là 'xmlhttp.setRequestHeader ('Content-Type', 'application/json ') ' –

Các vấn đề liên quan