尝试从 html 表单和 Node.js 发送数据

Dev*_*fic 5 html javascript node.js

我只是尝试在不使用 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>
Run Code Online (Sandbox Code Playgroud)

节点.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')});
Run Code Online (Sandbox Code Playgroud)

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"
   }
  }
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

HPa*_*tel 0

我已经验证了你的代码,它工作得很好。

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

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

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