javascript - Ajax issue with posting to a node/express endpoint -


it's been bit since used jquery/ajax instead of axios connect endpoint, doing wrong here?

var express = require('express');  var app = express()  var bodyparser = require('body-parser');  var path = require('path');    var port = process.env.port || 3000;    app.use(bodyparser.json())  app.use(bodyparser.urlencoded({extended: true}))    app.use(function (req, res, next) {              res.setheader('access-control-allow-origin', '*');              res.setheader('access-control-allow-methods', 'get, post, options, put, patch, delete');              res.setheader('access-control-allow-headers', 'x-requested-with,content-type');              res.setheader('access-control-allow-credentials', true);            // pass next layer of middleware        next();    });    app.get('/', function(req, res) {    console.log(req.body);    res.sendfile(path.join(__dirname, '../public/src', 'index.html'))    })    app.listen(port, function(error) {    if(error){      console.log(error);    }    console.log('express listening on port: ', port);  })

and client side code is:

<html lang="en">    <head>      <title></title>      <meta charset="utf-8">      <meta name="viewport" content="width=device-width, initial-scale=1">      <script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgfzhoseeamdoygbf13fyquitwlaqgxvsngt4=" crossorigin="anonymous"></script>      <script>          function buttonclick() {              $.ajax({                  url: 'http://localhost:3000',                  type: 'post',                  data: {                      'see me?': 'yeah?'                  },                  datatype: 'json',                  success: function(data) {                      alert('this data: ', data)                  },                  error: function(error) {                      alert('this error: ', error)                  }              })          }      </script>  </head>    <body>      <h3>hello world</h3>          <button onclick="buttonclick()"> click me! </button>      </body>    </html>

whenever hit click me button, error:

post http://localhost:3000/ 404 (not found)  (anonymous) @ vm174:1  send @ jquery-3.2.1.min.js:4  ajax @ jquery-3.2.1.min.js:4  buttonclick @ (index):11  onclick @ (index):33  vm174:1 xhr failed loading: post "http://localhost:3000/".

does know why happening? way, i'm getting console log on server when refresh page. time console log should happening when ajax post gets called. seems called on each refresh.

you don't have post handler on server side, got handler.

change post or add new post endpoint server.

app.post('/', function(req, res) {    console.log(req.body);    ......  })


Comments

Popular posts from this blog

angular - Ionic slides - dynamically add slides before and after -

minify - Minimizing css files -

Add a dynamic header in angular 2 http provider -