Tuesday 16 May 2017

NodeJS Ajax request fails

I have an form I am trying to submit from client to Express but every time I get an error like:

Cannot POST /request_method

Below are the code which I am trying:

index.html

<form id="wizard-content" method="post">
   <label>File</label>
   <input type="file" name="some" id="rsome">
   <label>Value</label>
   <input type="text" name="valSome" id="perfect">
</form>
<button type="submit" id="submit_form">Finish</button>
    <script type="text/javascript">
        jQuery('#submit_form').click(function() {
            if (jQuery(this).text().toLowerCase() === "finish") {
                submitForm();
            }
        });
        var submitForm = function(){
            var formData = {
                    'perfect'        : $('#perfect').val(),
                    'rsome'            : $('#rsome')[0].files[0]
                };
            if(formData){
                $.ajax({
                    url : '/request_method',
                    type : 'POST',
                    data : formData,
                    contentType : false,
                    cache : false,
                    processData: false,
                    success : function(response){
                        console.log(response);
                    }, 
                    error : function(error){
                        console.log(error);
                    }
                });
            }
        }
    </script>

And in expressJs :

server.js

var express     = require('express');
var bodyParser  = require('body-parser')
app.use(bodyParser());
.
.
router.post('/request_method', function(req, res){
   console.log(req.body);
   console.log(req.ip);
});



via Venkatesh Shanmugham

No comments:

Post a Comment