我是后端开发和 ajax 的新手。我正在使用 node.js、express 和 ejs。我正在尝试发布一些数据,并使用 ajax 返回一个值。我不断收到 404 错误,我不确定为什么。另外,我使用了 express 生成器来创建项目,还安装了 body-parser。
这是我的 index.ejs 文件中的 ajax 请求。它位于 header 中的脚本标记内。
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 文件中的内容有关。这也可能是 express 生成器制作服务器的方式。同样,我是新手,所以这里的任何输入都会很棒。
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;
会不会是因为index页面是用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 文件中。如果您需要了解任何其他信息,例如其他文件的外观,我很乐意向您展示。
最佳答案
您必须将有效的 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);
});
}
关于javascript - 400 错误请求 : Node. js Express Ajax,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50526160/