Reputation: 1837
I'm new to node.js / express and I have a question. I'm searching this for hours.
I'm trying to make an admin panel for my basic blog and I need to POST:
title
& content
from input in HTML
to my panel.js
Here is what I tried:
Post data from HTML page, it works:
$(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"
});
});
});
And 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;
Error report:
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 Console :
POST http://127.0.0.1:3000/panel/save 500 (Internal Server Error)
Upvotes: 0
Views: 1083
Reputation: 10610
First, make sure you name your title
variable when you pass it into your ajax call by placing it in an object literal:
$.ajax({
type: "POST",
url: "/panel/save",
data: { title: title.value },
dataType: "json"
});
Next, change your router.get
to router.post
so it can accept the route. Next, you should be accessing your postdata through req.body
. Just make sure you're use
ing express's body-parser
somewhere in your app prior to this route declaration.
router.post('/save/', function(req, res) {
var t = req.body.title;
console.log("title :"+t);
});
Upvotes: 3