gpt4 book ai didi

javascript - Nodejs - Express JSON 解析器无法响应

转载 作者:搜寻专家 更新时间:2023-11-01 00:00:25 24 4
gpt4 key购买 nike

我的问题:一旦我用 JQuery 提交一个 JSON 对象到我使用 JSON 解析器(属于模块 body-parser)的 express 应用程序并尝试响应它,无论是 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>

最佳答案

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

关于javascript - Nodejs - Express JSON 解析器无法响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35901161/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com