【问题标题】:Trying to send data from a html form and Node.js尝试从 html 表单和 Node.js 发送数据
【发布时间】:2017-06-16 08:36:26
【问题描述】:

我只是想练习在不使用 Angular、React 或其他框架库的情况下将数据从静态 html 页面操作到 Node.Js。我已经安装了所有依赖项,并且节点正在为我的 index.html 提供服务,但是,我似乎无法让我的 post 方法工作。我什至无法将它用于 console.log 任何内容。我查看了其他堆栈溢出问题和文档,但似乎无法找出问题所在。

这是我的代码和文件结构。

HTML:

<form id="citySearchForm" action="http://127.0.0.1:3000/getcity" method="POST">

        <div>
            <p>Choose a city:</p>
            <input type="text" placeholder="Enter a city" id="getCitiesInput" name="city"></input>
            <input type="submit" value="submit">
        </div>

        <div id="weather"></div>

        <p><span id="temp"></span></p>

        <p><span id="wind"></span></p>

 </form>

node.js:

var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var urlencodedParser = bodyParser.urlencoded({ extended: false});

app.use(express.static('public'));
app.get('/index.html', function(req, res){
    res.sendFile(_dirname + "/" + "index.html");
})

app.post('/getcity', urlencodedParser, function(req, res){
    response = { city : req.body.city };
    console.log(response);
    res.end(JSON.stringify(response));
})

app.listen(3000, function() { console.log('listening')});

json:

{
  "name": "basic_weather_api",
   "version": "1.0.0",
   "description": "Just a basic api call",
   "main": "server.js",
   "scripts": {
      "test": "echo \"Error: no test specified\" && exit 1",
      "start": "node server.js"
   },
   "author": "",
   "license": "ISC",
   "dependencies": {
     "body-parser": "^1.16.0",
     "express": "^4.14.1"
   }
  }

【问题讨论】:

  • 我刚刚在本地进行了测试,在将_dirname 更改为__dirname 后它工作正常。您是否在编辑文件后结束/杀死节点服务器?
  • 我进行了更改并重新启动了节点。我刚刚更新到 v 1.11.0 也许与它有关。我被难住了。
  • 这是金子。我几乎已经去 deepweb 报废了这些信息。 TY

标签: javascript html node.js


【解决方案1】:

我已经验证了你的代码,它运行良好。

在使用 city = Test 提交时,我在浏览器中看到了这个 Json 响应:{"city":"Test"}

另外,我可能会看到您打印的日志语句。但请记住您的console.log() 语句是node.js 服务器代码的一部分,这意味着您的日志语句将打印在服务器日志中,而不是在浏览器控制台中。如果您使用node server.js 从终端运行您的节点服务器,您将看到您的日志打印在终端中。

如果你多次修改了依赖版本,请删除node_modules目录并尝试再次运行npm install

【讨论】:

  • 不确定是否是因为更新的依赖关系,但帖子只是不会登录终端。我将我的 package.json 添加到帖子线程中。
  • @LonnieMcGill 我刚刚也尝试了您的 package.json 并且对我来说效果很好。如果您尝试多次更改依赖项的版本,只需删除 node_modules 文件夹并再次运行 npm install
  • 我重新安装了所有东西,它工作正常。设置依赖项后,我更新到节点 1.11.0。没想到我需要删除 json 和 node 模块,因为我没有更改依赖版本,但看起来你这样做了。谢谢。
猜你喜欢
  • 1970-01-01
  • 2013-10-17
  • 1970-01-01
  • 2013-03-12
  • 2020-04-01
  • 2017-01-05
  • 1970-01-01
  • 2019-03-11
  • 1970-01-01
相关资源
最近更新 更多