我是node.js / express的新手,我有一个问题。我正在搜索这几个小时。
我正在尝试为我的基本博客创建一个管理面板,我需要发布POST:
title
&来自HTML输入的content
到我的panel.js
以下是我的尝试:
从HTML页面发布数据,它有效:
$(document).ready(function() {
$('#but').click(function(e) {
e.preventDefault();
var title = document.getElementById('title');
$.ajax({
type: "POST",
url: "/panel/save",
data: title.value,
dataType: "json"
});
});
});
panel.js
var express = require('express');
var router = express.Router();
var app = express();
router.get('/', function(req, res) {
res.render('panel_html');
});
/* mysql things */
router.get('/save/', function(req, res) {
var t = req.params.title;
console.log("title :"+t);
});
module.exports = router;
错误报告:
14 Aug 20:49:33 - [nodemon] restarting due to changes...
14 Aug 20:49:33 - [nodemon] starting `node app.js`
GET /panel/ 304 11ms
GET /lib/semantic/build/packaged/javascript/semantic.js 304 4ms
GET /lib/semantic/build/packaged/css/semantic.css 304 5ms
GET /stylesheets/style.css 304 7ms
GET /lib/semantic/build/packaged/fonts/icons.svg 304 1ms
GET /lib/semantic/build/packaged/fonts/icons.woff 304 0ms
Error: Failed to lookup view "error" in views directory "...site/views"
at Function.app.render (...site/node_modules/express/lib/application.js:492:17)
at ServerResponse.res.render (...site/node_modules/express/lib/response.js:802:7)
at Layer.module.exports [as handle] (...site/app.js:74:9)
at trim_prefix (...site/node_modules/express/lib/router/index.js:235:17)
at ...site/node_modules/express/lib/router/index.js:208:9
at Function.proto.process_params (...site/node_modules/express/lib/router/index.js:269:12)
at IncomingMessage.next (...site/node_modules/express/lib/router/index.js:199:19)
at fn (...site/node_modules/express/lib/response.js:797:25)
at Function.app.render (...site/node_modules/express/lib/application.js:494:14)
at ServerResponse.res.render (...site/node_modules/express/lib/response.js:802:7)
POST /panel/save 500 11ms - 1.13kb
Google Chrome控制台:
POST http://127.0.0.1:3000/panel/save 500 (Internal Server Error)
答案 0 :(得分:3)
首先,确保在将title
变量放入ajax调用时将其命名为对象文字,从而将其命名为<{1}}变量:
$.ajax({
type: "POST",
url: "/panel/save",
data: { title: title.value },
dataType: "json"
});
接下来,将您的router.get
更改为router.post
,以便它可以接受该路线。接下来,您应该通过req.body
访问您的postdata。在此路线声明之前,请确保您在应用中的某个地方use
router.post('/save/', function(req, res) {
var t = req.body.title;
console.log("title :"+t);
});
{{1}} {/ 3}}。
{{1}}