【发布时间】: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