ajax – 将jQuery JSON对象发布到NodeJs Restify
发布时间:2020-12-16 02:52:46 所属栏目:百科 来源:网络整理
导读:我想知道为什么在/:参数中发布一个简单的 JSON字符串来解析它是如此困难.我遵循了许多例子,但没有发现任何具体的东西. 我在前端有以下代码. $("#btnDoTest").click(function() { var jData = { hello: "world" }; var request = $.ajax({ url: "http://loca
我想知道为什么在/:参数中发布一个简单的
JSON字符串来解析它是如此困难.我遵循了许多例子,但没有发现任何具体的东西.
我在前端有以下代码. $("#btnDoTest").click(function() { var jData = { hello: "world" }; var request = $.ajax({ url: "http://localhost:8081/j/",async: false,type: "POST",data: JSON.stringify(jData),contentType: "application/javascript",dataType: "json" }); request.success(function(result) { console.log(result); }); request.fail(function(jqXHR,textStatus) { alert("Request failed: " + textStatus); }); }); 如果我在j /之后连接param,我在发送简单文本方面是成功的.但是我想要发送的是像这样的对象{hello:“world”}并在nodeJS中重新构建它并使用它. – 编辑: This is my nodejs file /* the below function is from restifylib/response.js */ var restify = require("restify"); /* create the restify server */ var server = restify.createServer({ }); server.use(restify.bodyParser({ mapParams: true })); server.use( function crossOrigin(req,res,next){ res.header("Access-Control-Allow-Origin","*"); res.header("Access-Control-Allow-Headers","X-Requested-With"); return next(); } ); server.post('/j/',function (req,next) { //res.send(201,"REceived body: "+JSON.stringify(req.params)); res.send(201,"REceived body: "+JSON.stringify(req.params)); return next(); }); var port = 8081; server.listen(port); console.log("Server listening on port " +port) 任何帮助将不胜感激. 0X 解决方法
我终于搞定了.
– 前端代码 $("#btnDoTest").click(function() { var request = $.ajax({ url: "http://localhost:3000/j",data: { blob: {wob:"1",job:"2",ar:[1,2,{a:'b'}]} },contentType: "application/x-www-form-urlencoded",//This is what made the difference. dataType: "json",}); request.success(function(result) { console.log(result); }); request.fail(function(jqXHR,textStatus) { alert("Request failed: " + textStatus); }); }); NodeJs服务 /* the below function is from restifylib/response.js */ var restify = require("restify"); /* create the restify server */ var server = restify.createServer({ }); server.use(restify.bodyParser()); server.use(restify.CORS()); server.post('/j/',function(req,next) { res.header("Access-Control-Allow-Origin","X-Requested-With"); // req.params == data on jquery ajax request. res.send(200,JSON.stringify(req.params)); console.log(req.params.blob.ar[2].a) res.end(); return next(); }); var port = 3000; server.listen(port); console.log("Server listening on port " + port) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- ruby – 为什么[] .all?{| a | a.include?(‘_’)}返回tr
- asp.net 利用NPOI导出Excel通用类的方法
- Fetch XML and ConditionExpression operators
- Error occured processing XML 'Cannot find class [sp
- warning: check_safe_call: could not restore current fra
- c语言正则表达式匹配URL问题
- 基于PostgreSQL中的时间戳的移动平均线
- 学习使用SQLite(版本3.7.4)(中H ) ?
- 如何在低内存系统上使用RVM编译ruby?
- LD_PRELOAD用于C类方法