簡體   English   中英

嘗試從html表單和Node.js發送數據

[英]Trying to send data from a html form and 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"
   }
  }

在此輸入圖像描述

我已驗證您的代碼,它的工作完全正常。

在使用city = Test提交時,我在瀏覽器中看到這個Json響應: {"city":"Test"}

另外,我也會看到你的日志聲明打印出來。 但請記住,您的console.log()語句是node.js服務器代碼的一部分,這意味着您的日志語句將打印在服務器日志中而不是打印機控制台中。 如果使用node server.js從終端運行節點服務器,則會在終端中看到您的日志。

如果您多次修改了依賴項的版本,請刪除node_modules目錄並嘗試再次運行npm install

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM