首页 > 解决方案 > 400 错误请求:Node.js Express Ajax

问题描述

我是后端开发和 ajax 的新手。我正在使用 node.js、express 和 ejs。我正在尝试发布一些数据,并使用 ajax 返回一个值。我不断收到 404 错误,我不知道为什么。另外,我使用 express 生成器来创建项目,并且还安装了 body-parser。

这是我的 index.ejs 文件中的 ajax 请求。它位于标头的脚本标记中。

function post() {
    $.ajax({
        type: "POST",
        url: "/test",
        data: 'TEST',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
    }).done(function (data) {
        console.log("Did it work? "+ data);
    });
}

一旦按下按钮,ajax 就会执行,我收到 400 错误请求。我认为这可能与 index.js 文件中的内容有关。这也可能是快递生成器制作服务器的方式。同样,我是新手,所以这里的任何输入都会很棒。

index.js:

var express = require('express');
var router = express.Router();
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.json()); // support json encoded bodies
app.use(bodyParser.urlencoded({ extended: true })); // support encoded bodies


/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index');
});
app.post('/test', function(req, res) {
    console.log(req.body);
    res.type('json');
    res.send("hi");
  });
module.exports = router;

难道是因为索引页面是使用ejs渲染的?

提前致谢!


更新:400 已修复,现在得到 404

400 错误是由于我尝试发送对象而不是字符串引起的。现在,我收到 404 错误。根据要求,我的文件结构如下。

  .
  ├── app.js
  ├── bin
  │   └── www
  ├── package.json
  ├── public
  │   ├── images
  │   ├── javascripts
  │   └── stylesheets
  │       └── style.css
  ├── routes
  │   ├── index.js
  │   └── users.js
  └── views
      ├── error.ejs
      ├── index.ejs
      └── layout.ejs

  7 directories, 9 files

我仍在努力掌握这一点,生成器为我制作了文件。据我了解,bin 文件夹中的 www 文件是启动脚本。app.js 文件调用其他所有内容。我正在尝试将 post 方法放在 index.js 文件中,但我不确定它是否应该放在那里或者可能放在 app.js 文件中。如果您需要了解任何其他信息,例如其他文件的外观,我很乐意向您展示。

标签: javascriptnode.jsajaxexpressejs

解决方案


您必须将有效的 json 字符串传递给数据,例如

function post() {
    $.ajax({
        type: "POST",
        url: "/test",
        data: JSON.stringify({data: 'TEST'}),
        contentType: "application/json; charset=utf-8",
        dataType: "json",
    }).done(function (data) {
        console.log("Did it work? "+ data);
    });
} 

推荐阅读