Post request with ajax jquery reterns a 404 status

I have a NodeJS express application and i am trying to post data to an endpoint in the server, using jquery ajax post request, but i seem to get an XHR 404 Not Found error and i dont know whats causing it, i am certain my URL is correct, i apoligise in advance if this is a stupid question. I am still learning JavaScript and web programing in general so i am unfamiliar with some things, so i would be glad to get some help, thanks.

this is my code:

index.ejs—

<title>Test</title>
<div class="container" style="background-color: blue; height: 400px; width: 400px;">
    <h1 id="title1" style="color: white;">Title</h1>
</div>

<script src="post_req.js"></script>

app.js—

const express = require("express");
app = express();

app.use(express.static('static'))

app.get('/', (req, res) => {
    console.log(req.body)
    res.render('index.ejs')
})

app.listen(4500, () => {
    console.log('Listening');
})

and my jquery file post_req.js—

$(document).ready(function() {
    $('.container').click(function() {
        $.ajax({
            url: '/',
            type: 'post',
            contentType: 'application',
            data: {
                data: 'Test'
            },
            success: function() {
                console.log('success')
            }
        })
    })

})

Hi @vasko4da4gama, looks like there simply isn’t a post route in your application… you need something like this:

app.post('/', () => {
  // ...
})

You can read about route methods here.

1 Like

Thank you, this fixed my issue!

1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.