简体   繁体   中英

How to connect my website to my node app?

So I am trying to send test data to my node app using ajax. I'm not sure what I'm doing wrong to post the information. I have added this to my script to my html:

index.html

<script type="text/javascript">
    jQuery(function() {
        console.log('hello');
        var $ = jQuery;
        $(window).ready(function() {

            console.log('hello');
                $.ajax({
                    dataType: 'jsonp',
                    xhrFields: {
                    withCredentials: true,

                    },
                    url: 'http://localhost:3000',

                    data: '{"data": "TEST"}',
                    type: 'POST',

                    success: function () {

                        console.log('Success: ');
                    },
                    error: function (xhr, status, error) {
                        console.log('Error: ' + error.message);

                    },

            });
        });
        });
    </script>

I am trying to receive this information from my node app but I'm not sure how to.

server.js

var express = require('express')
  , cors = require('cors')
  , app = express()
  , http = require('http');

app.use(cors());

var server = http.createServer(app, function(req, res) {
        var body = "";
         req.on('data', function (chunk) {
            body += chunk;
         });
         req.on('end', function () {
            console.log(body);
            res(body);
         });
}).listen(3000, function(){
  console.log('CORS-enabled web server listening on port 80');
});

However, I keep getting this error on website's console:
'GET http://localhost:3000/?callback=jQuery214011563337640836835_1442781076103& {%22data%22:%20%22TEST%22}&_=1442781076104 n.ajaxTransport.a.send @ jquery.js:8698n.extend.ajax @ jquery.js:8166(anonymous function) @ final.html:534n.Callbacks.j @ jquery.js:3099n.Callbacks.k.fireWith @ jquery.js:3211n.extend.ready @ jquery.js:3417I @ jquery.js:3433 final.html:550 Error: undefined'

If this is successful I am trying to create a form that posts the input to my node app that can process it with stripe.

I recommend following the Express JS Getting Started guide found here: http://expressjs.com/starter/installing.html . Specifically, look at the sections on Express generator and Basic routing.

In your code, you are requiring the Express module, but not actually using it, and this module is the most robust way to handle posts in node.js.

If you still want to use the http module for handling post requests, check this out: Node.js server that accepts POST requests . It also has more information on using Express JS

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM