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

我只是试图操作数据从一个静态的HTML页面到Node.Js,而不使用Angular,React或其他框架库。 我已经安装了所有的依赖关系,节点正在服务我的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" } } 

在这里输入图像描述

我已经validation你的代码,它工作得很好。

在提交城市=testing,我在浏览器中看到这个JSON响应: {"city":"Test"}

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

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