【问题标题】:How to connect my website to my node app?如何将我的网站连接到我的节点应用程序?
【发布时间】:2015-09-21 05:11:11
【问题描述】:

所以我正在尝试使用 ajax 将测试数据发送到我的节点应用程序。我不确定我在发布信息时做错了什么。我已将此脚本添加到我的 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>

我正在尝试从我的节点应用程序接收此信息,但我不知道如何。

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');
});

但是,我在网站的控制台上不断收到此错误:
'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(匿名函数) @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 错误:未定义'

如果成功,我将尝试创建一个表单,将输入发布到我的节点应用程序,该应用程序可以使用条带处理它。

【问题讨论】:

    标签: javascript jquery ajax node.js


    【解决方案1】:

    我建议遵循此处的 Express JS 入门指南:http://expressjs.com/starter/installing.html。具体来说,请查看 Express 生成器和基本路由部分。

    在您的代码中,您需要 Express 模块,但实际上并未使用它,并且此模块是在 node.js 中处理帖子的最可靠的方式。

    如果您仍想使用 http 模块来处理 post 请求,请查看:Node.js server that accepts POST requests。它还有更多关于使用 Express JS 的信息

    【讨论】:

    • 我已经上传了我的网站。我是否必须将其取下并使用fs.readFileSync('index.html') 才能使用节点?我可以将 html 和 node 文件分开吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-08
    • 1970-01-01
    • 2014-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多