node.js - ajax 使用 Node 和 Nginx 发布 500 内部服务器错误
问题描述
我正在尝试发布到我的节点服务器,但我收到“加载资源失败”500 内部服务器错误代码,我不知道为什么。
这是Node所说的错误。
我的服务器代码:
var db = null
var app = null
//console.error(config.mongohq)
mongo.init(
{
name: config.mongohq.name,
host: config.mongohq.host,
port: config.mongohq.port,
username: config.mongohq.username,
password: config.mongohq.password,
},
function(res){
db = res
var prefix = '/assignment2/'
app = express()
// Configuration
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing
//multer_upload = multer({ dest: './images' }).any();
app.get(prefix + 'search/:query', search);
app.post(prefix + ":chicken/log", log)
app.listen(3009)
console.error('Server listening on port 3009')
},
function(err){
console.error(err)
}
)
function log(req,res)
{
var list = JSON.parse(req.body.items);
console.log(hello)
for (var i = 0; i <list.length; i++)
{
fs.appendFile("assignment2/Foghorn/log.dat", JSON.stringify(list[i]));
}
}
我的客户端邮政编码:
//Clear the local storage and array of the user's choice of chicken type
var server = "http://xxxx:xxxx/assignment2/";
function sendLogs()
{
clearFields();
var path;
if(chickenNumber == 0)
{
var items = {logs: foghorn_items};
path = server + "Foghorn/log";
$.ajax({
url: path,
method: 'POST',
dataType: 'JSON',
data: items,
success: function (data){
alert('Logs sent to file');
}
});
// foghorn_items.length = 0;
// localStorage.removeItem("foghorn_items");
}
出于安全原因隐藏我的 ip 和端口。
我很确定我的 log.dat 文件在 Nginx 的 html 文件夹中的 assignment2/Foghorn 中
根据节点,错误指向 log() 方法的第一行
知道问题是什么吗?
解决方案
代码中的违规行是var list = JSON.parse(req.body.items)
.
但req.body.items
它不是文本字符串,它是一个带有正文参数的对象。所以,当然 JSON.parse 拒绝它。
JSON 解析器中间件 ( app.use(bodyParser.json())
) 解析您请求中的 JSON 并将结果放在req.body
. 因此,您无需再次解析它。
推荐阅读
- auth0 - 如何在 Auth0 租户中使用自动迁移的自定义数据库中的用户包含经过验证的电子邮件状态?
- spring - Tomcat上的rest api后端是否应该允许keepalive请求?
- node.js - 通过 VPN 路由 node.js 请求
- android - 连接耳机时,WebRTC android应用程序正在创建回声
- c++ - 简单网格移动练习中的 switch 语句默认值
- java - 如何修复循环以使代码不会在最后一个数字后面打印“+”
- javascript - 在 WP Rest API 中获取基于 WooCommerce 产品 URL 的 features_image
- python - 关于 Flask + Multiprocessing + Tensorflow 的问题
- ruby-on-rails - FactoryBot create_list 重复记录 - 唯一性验证失败
- php - 如何在php中一一循环遍历数组