[英]400 Bad Request: 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文件中的內容有關。 這也可能是Express Generator生成服務器的方式。 再次,我是新來的,所以這里的任何輸入都會很棒。
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);
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.