Trying to send data from html form and Node.js

I am trying to just manipulate data from a static html page to Node.Js without using Angular, React or other framework libraries. I installed all my dependencies and node maintains my index.html, however I cannot get my mail method to work. I can not get it even console.log anything. I examined other stack overflow problems and docs, but I seem to be unable to understand this problem.

Here is my code and file structure.

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"
   }
  }

enter image description here

+4
source share
1 answer

I checked your code and it works great.

On submit with city = Test, I see this Json answer in the browser: {"city":"Test"}

, , . , console.log() node.js, , , . node node server.js, , .

, node_modules npm install.

0

Source: https://habr.com/ru/post/1668338/


All Articles