javascript - 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 文件中。如果您需要了解任何其他信息,例如其他文件的外观,我很乐意向您展示。
解决方案
您必须将有效的 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);
});
}
推荐阅读
- ruby-on-rails - Trix 编辑器在 Heroku 中不工作,但在 localhost 上工作正常
- selenium-webdriver - Pycharm:机器人框架:SessionNotCreatedException:消息:会话未创建:此版本的 ChromeDriver 仅支持 Chrome 版本 75
- python - 在 Python 中制作加权评分量表
- arduino - 如何修复“aes128_enc_single”未在此范围内声明”
- grep - 在匹配的单词后显示 X 个字符
- angular - 为什么在 Angular 中通过 HTTP 使用 Observable
- javascript - 防止多次调用相同的javascript函数
- visual-studio - 将代码段插入 Visual Studio 2017 时如何编辑文字
- javascript - 如何在 javascript 的纯函数中更新对象?
- java - 如何在 Spring-Data-MongoDB 中使用 @Query 组合 AND 和 OR 子句?