首页 > 解决方案 > 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() 方法的第一行

知道问题是什么吗?

标签: node.jsajax

解决方案


代码中的违规行是var list = JSON.parse(req.body.items).

req.body.items它不是文本字符串,它是一个带有正文参数的对象。所以,当然 JSON.parse 拒绝它。

JSON 解析器中间件 ( app.use(bodyParser.json())) 解析您请求中的 JSON 并将结果放在req.body. 因此,您无需再次解析它。


推荐阅读