【问题标题】:Use Express server to control a nodejs application使用 Express 服务器控制 nodejs 应用程序
【发布时间】:2018-08-11 12:30:17
【问题描述】:

我有一个 node.js 应用程序,用于与另一台服务器提供的 REST API 进行交互。我想使用 express.js 公开一个 Web 界面(html + css + javascript)以控制第一个应用程序。

如何让浏览器与服务器通信并让它执行 node.js 操作,例如从该机器使用 http 或写入其文件系统?我尝试使用 XMLHttpRequest,但 HTTP 请求是由我的本地 PC 而不是从我的服务器发送的。

我找到的唯一解决方案是在我的 Web 界面的 javascript 中使用 XMLHttpRequest 来调用我服务器上的一些中间件函数,但是我遇到了一些问题:当我发出 POST 请求时,我无法从服务器读取数据。我使用 FormData 及其 append 方法来制作 POST 请求的“正文”,然后在 express 中使用 body-parser 来读取该正文,但结果始终为空。还尝试更改标题的“Content-Type”。

有什么建议吗?有没有比我更好的解决方案(我认为它效率不高)?

【问题讨论】:

  • 使用 nodeJS 服务器作为“代理”是正确的方法,没有代码很难判断你的版本出了什么问题。

标签: javascript node.js http express


【解决方案1】:

正如 Jonas 所指出的,使用节点服务器作为代理是正确的方法。

我正在为前端和后端应用程序提供示例代码。希望对您有所帮助。

  • 前端应用代码
<html>
  <head>
    <script type="text/javascript">
      function sendData(data) {
        if (!data) {
          // lets define some dummy data for testing
          data = { somekey: "somevalue", anotherkey: "anothervalues" };
        }
        var XHR = new XMLHttpRequest();
        var FD = new FormData();

        // Push our data into our FormData object
        for (name in data) {
          FD.append(name, data[name]);
        }

        // Define what happens on successful data submission
        XHR.addEventListener("load", function(event) {
          alert("Yeah! Data sent and response loaded.");
          alert(event.target.responseText);
        });

        // Define what happens in case of error
        XHR.addEventListener("error", function(event) {
          alert("Oops! Something went wrong.");
        });

        // Set up our request
        XHR.open("POST", "http://path/to/your/nodejs/server/app");

        // Send our FormData object; HTTP headers are set automatically
        XHR.send(FD);
      }
    </script>
  </head>

  <body>
    <button onclick="sendData()">Send Test Request to the Server</button>
  </body>
</html>
  • 后端应用代码
常量 http = 要求('http'); 常量表达 = 要求(“表达”); const bodyParser = require('body-parser'); 常量应用程序 = 快递(); app.use(bodyParser.urlencoded({extended: false })); app.get('/', (req, res) => res.send('是的!服务器已启动!发布一些数据')); app.post('/', (req, res) => { // 您将在 req.body 中看到发布的数据,仅出于测试目的将其返回给调用用户 res.json(req.body || {}); }); 常量服务器 = http.createServer(app); server.listen(3000); server.on('error', console.error); server.on('listening', () => console.log('Listening on 3000')); process.on('exit', (code) => console.warn('服务器以code=' + code));

请注意,要运行此后端应用程序,您必须安装以下 npm 包:express、body-parser

【讨论】:

  • req.body 对我来说是一个空对象。我检查了FD对象是否为空而不是,所以我不明白我错在哪里......
猜你喜欢
  • 2019-03-07
  • 1970-01-01
  • 1970-01-01
  • 2018-06-18
  • 1970-01-01
  • 1970-01-01
  • 2016-08-01
  • 2017-06-08
相关资源
最近更新 更多