使用javascript http发送和接收数据
我使用XMLHttpRequest从javascript发送json格式的数据,并在node.js文件中接收数据,如下所示 client.js使用javascript http发送和接收数据,javascript,ajax,node.js,xmlhttprequest,Javascript,Ajax,Node.js,Xmlhttprequest,我使用XMLHttpRequest从javascript发送json格式的数据,并在node.js文件中接收数据,如下所示 client.js $.ajax({ type: "POST", dataType: 'json', data: JSON.stringify(Idata), url: AjaxURL, success: function (result) { return true; } }); var http = r
$.ajax({
type: "POST",
dataType: 'json',
data: JSON.stringify(Idata),
url: AjaxURL,
success: function (result) {
return true;
}
});
var http = require('http');
console.log("server initialized");
var server = http.createServer(function (req, response) {
req.on('data', function (data) {
var d = JSON.parse(data);
console.log("data : " + d.OperationType);
});
req.on('end', function () {
response.end();
});
}).listen(3000);
server.js
$.ajax({
type: "POST",
dataType: 'json',
data: JSON.stringify(Idata),
url: AjaxURL,
success: function (result) {
return true;
}
});
var http = require('http');
console.log("server initialized");
var server = http.createServer(function (req, response) {
req.on('data', function (data) {
var d = JSON.parse(data);
console.log("data : " + d.OperationType);
});
req.on('end', function () {
response.end();
});
}).listen(3000);
现在,我已成功获取operationtype的值,但客户端浏览器显示此错误:
无法加载XMLHttpRequest。请求的资源上不存在“Access Control Allow Origin”标头。因此不允许访问源“”。请执行以下操作:
client.js
中,在发送之前立即输出值Idata
(使用console.log
)server.js
中,在接收到值后立即输出值data
(使用console.log
)data
被视为一个对象,store+=data
不是一个好主意,因为这意味着您正试图将对象添加到(空)字符串中。
(可能导致对象返回“[object object]”或类似的内容)主要问题是您正在发出一个
“GET”
请求。无法使用XMLHttpRequest“GET”
请求上载数据有效负载/HTTP请求正文。请参阅:“如果存储的方法是GET,请将数据参数设置为null。”
为了发送数据,您应该发出“POST”
请求,在这种情况下:
xmlhttp.open("POST", AjaxURL, true);
回应最新问题:
出于安全原因,将不允许您的AJAX请求访问托管在localhost:3000
的服务器,除非AJAX请求是从localhost:3000
提供的页面启动的,或者您告诉您的服务器允许“跨源”请求。后者可以通过在服务器上添加以下行来实现:
response.setHeader("Access-Control-Allow-Origin", "*");
这将设置一个标头,告诉浏览器允许AJAX请求到
localhost:3000
,即使请求是从一个未由localhost:3000
提供服务的页面启动的。我从客户端发送的Idata如下所示:var Idata={'OperationType':'GID','DNS':''+objName+'','fn':'SetGUID'};Idata具有值[object]在客户端和服务器端谢谢。post运行良好,但错误现在显示在客户端浏览器上,我在更新的问题中提到了这一点。我更新了我的答案。如果您还有任何其他问题,您应该创建一个新问题,而不是修改此问题。显著地修改您以前的问题会使其他人难以理解谢谢David,现在它工作得很好。这个答案让我的工作轻松了很多,再次感谢