在Node / Express中将用户输入从前端传递到后端

问题描述 投票:0回答:3

我正在尝试制作一个简单的应用程序来分析一堆推文。

首先,基本文件结构为:

在首页(index.html)上,用户在文本输入字段中输入Twitter用户名:

<input type="text" id="user-input" maxlength="25">
<button id="grabInput" onclick="storeInput()">Submit</button>

storeInput()函数位于后端的app.js文件中,该文件可以访问我用来访问Twitter API的Node模块。

我尝试将脚本元素中的文件路径更改为<script src="../app.js"></script>但是它不起作用。

谁能帮助我了解Node / Express应用程序中前端与后端的通信方式? 我很沮丧,因为我的应用程序的每个“半部分”都可以正常测试,但是我无法连接它们。

谢谢!

javascript node.js twitter
3个回答
1
投票

您需要了解Web应用程序的基础知识。

您不能直接从浏览器调用服务器端storeInput() JavaScript函数。

您的Web应用程序包含两个部分。 服务器端和客户端。

您现有的storeInput()试图在客户端执行,例如。 在浏览器中。 因此,您需要它向服务器发出请求并配置服务器以将该请求重定向到app.js 然后, app.js将使用nodeModule Twitter API获取数据并相应地响应请求。 然后,您可以根据服务器发送的响应来呈现客户端。

但是,如果您只想简单地显示来自Twitter的帖子而无需任何服务器端操作,则不必执行所有这些操作。 Twitter有一个API,您可以直接从客户端调用它并提取数据。如果您只想显示帖子,我强烈建议您使用Twitter API,因为它更快,更简单,更安全。


1
投票

应该应用通用形式post + express的执行示例

的HTML

<form method="POST" action="/foo-route">
   <input type="text" id="bar" name="bar" />
   <button type="submit">Send</button>
</form>

快速路线

router.post('/foo-route',(req,res) => {
  if(typeof req.body.bar === 'undefined'){
    // The parameter is missing, example response...
    res.status(400).json({ error: 'missing parameter bar', data: null }); // Only an  example
    return;
  }

  let bar = req.body.bar;

  res.status(200).json({ error: null, data: bar }); // We received the value and only to show the example, returns it in a json within the key 'data'

});

上面的示例显示了如何处理表单中的输入文本,以及如何在后端正确处理。 适应您的麻烦应该很容易。 让我知道是否。 请记住,在输入中添加字段名称=“ ..”。 <input type="text" id="something" name="myGreatName" /> ,然后使用req.body.myGreatName进行访问。


0
投票

为什么不使用HTML get表单? 这样,您可以将用户输入发送回服务器,在其中您可以使用路由来处理此输入,与twitter API进行交互,然后呈现结果。

© www.soinside.com 2019 - 2024. All rights reserved.