我的问题:一旦我用JQuery向我的快递app提交一个JSON对象,它使用JSON解析器(属于模块体解析器)并尝试回复它,无论是res.send还是res.render,它什么也没做。我尝试将html作为html响应直接输出回客户端。 另一方面,在我的网站的同一页面上,我尝试了常规的身体解析器,并且响应正常。 这是我的JSON监听器:
controller.js:
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var jsonParser = bodyParser.json();
var urlencodedParser = bodyParser.urlencoded({ extended:
false });
app.post('/video', jsonParser, function(req, res) {
res.send("hi"); //nothing happens
console.log(req.body.time); //works, i get the data
console.log(req.body.src); //works, i get the data
});
提交给它的表单:
的index.html
...mywebsite code, uses jquery
fu();
function fu(){
var vid = document.getElementById("vid");
var time = vid.currentTime;
var src = vid.currentSrc;
$.ajax({
type: "POST",
url: "/video",
data: JSON.stringify({time: time, src: src }), //the data is parsed fine
dataType: 'json',
contentType: 'application/json'
});
//alert("current time: " + time);
};
现在,我尝试了一个带有身体解析器的简单表单,它在同一个网站上工作正常(我把它放在那里只是为了看看它是否可行):
controller.js
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var jsonParser = bodyParser.json();
var urlencodedParser = bodyParser.urlencoded({ extended:
false });
app.post('/person', urlencodedParser, function(req, res){
res.send('Thanks!');
console.log(req.body.firstname);
console.log(req.body.lastname);
});
此人形式:
<form method="POST" action="/person">
Firstname: <input type ="text" id="firstname"
name="firstname"><br>
Lastname: <input type ="text" id="lastname"
name="lastname">
<input type="submit" value="sumbit">
</form>
答案 0 :(得分:1)
您需要在$.ajax
请求后处理客户端中的响应。设置done
函数以处理成功回调:
$.ajax({
type: "POST",
url: "/video",
data: {time: time, src: src },
dataType: 'json',
contentType: 'application/json'
})
.done(function( data, status, xhttp) {
// put the data in the DOM
document.getElementById("hi").text(data);
});
答案 1 :(得分:0)
嗯,看起来很简单 - 您没有在第二个代码段中使用jsonParser
- 只是urlencodedParser
,这在这里不正确。所以看起来应该是这样的:
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var jsonParser = bodyParser.json();
var urlencodedParser = bodyParser.urlencoded({ extended: false });
app.post('/person', jsonParser, function(req, res){
res.send('Thanks!');
console.log(req.body.firstname);
console.log(req.body.lastname);
});
答案 2 :(得分:0)
您可以尝试使用polyfill&#34; fetch&#34;而是jQuery:
function getResponse (url) {
return fetch(url, {
method: 'post',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({ time, src })
})
.then(response => response.json())
.then(data => {
console.log('request succeeded with JSON response', data)
})
.catch(error => {
console.log('request failed', error)
})
}
我认为它看起来会好得多。它可以在服务器端使用。 文档:https://github.com/github/fetch