Reputation: 101
I'm new to back end development and ajax. I'm using node.js, express, and ejs. I'm trying to post some data, and return a value using ajax. I keep getting a 404 error and I'm not sure why. Also, I used the express generator to create the project, and also installed body-parser.
Here's the ajax request that's in my index.ejs file. It's within a script tag in the 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);
});
}
Once a button is pressed that ajax executes, and I get a 400 bad request. I think it might be something to do with what's in the index.js file. It might also be the way that the express generator made the server. Again, I'm new to this so any input here would be great.
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;
Could it be because the index page is rendered using ejs?
Thanks in advance!
Update: 400 fixed, now getting 404
The 400 error was caused by my trying to send an object rather than a string. Now, I'm getting a 404 error. As requested, my file structure is below.
.
├── 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
I'm still trying to get the grasp of this, and the generator made the files for me. To my understanding, the www file within the bin folder is the startup script. The app.js file is calls everything else. I'm trying to put the post method within the index.js file, but I'm not exactly sure if it should go there or maybe in the app.js file. If you need to know any other info, like what the other files look like I'd be glad to show you.
Upvotes: 1
Views: 3645
Reputation: 5069
You must pass a valid json string into data, something like
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);
});
}
Upvotes: 2