This is the seventh day of my participation in the August More text Challenge. For details, see: August More Text Challenge

Use Node to process form GET requests

Form format

For an HTML form to be able to submit data by clicking the Button, it must have the following elements:

  1. The form has an action attribute, which tells the browser where to send the data.
  2. Each input field should have a name attribute, which helps us locate what we are entering.
  3. The type property of a button is submit.
<form action="/pinglun" method="get">
    <div class="form-group">
        <label for="input_name">Your name</label>
        <input type="text" class="form-control" required minlength="2" maxlength="10" id="input_name"
            name="name" placeholder="Please write your name.">
    </div>
    <div class="form-group">
        <label for="textarea_message">Message content</label>
        <textarea class="form-control" name="message" id="textarea_message" cols="30" rows="10" required
            minlength="5" maxlength="20"></textarea>
    </div>
    <button type="submit" class="btn btn-default">published</button>
</form>
Copy the code

Server uses Node’s core module URL (converts URL strings to objects)

  • Introducing url Module
const urlParse = require('url')
Copy the code
  • Parse a URL string into a URL object
const parseObj = urlParse.parse(url,true);
Copy the code
  • Get the request path (the request path does not contain the query string)
const pathname = parseObj.pathname;
Copy the code
  • Gets the data sent from the form
parseObj.query
Copy the code

Redirect client requests

  • First, a 302 status code is sent to the client for temporary redirection.
res.statusCode = 302;
Copy the code
  • Send the client to the specified path via the response header (the path below is the root path)
res.setHeader('Location'.'/');
Copy the code

Two types of exposure in Node

Use exports.xxx for exposure (everything you need to expose is in one object)

With this type of exposure, an object is exposed, as shown in the following example:

  • a.js
const test = require('./b');
console.log(test);
Copy the code
  • b.js
const foo = 'hello';
exports.foo = foo;
Copy the code

We call a, and the output is as follows

{foo: 'hello'}Copy the code

Use module.exports = XXX (this exposes XXX, we recommend using this method in the actual development process)

  • a.js
const test = require('./b');
console.log(test);
Copy the code
  • b.js
const foo = 'hello';
module.exports = foo;
Copy the code

A.js is called, and the output is as follows:

helloCopy the code

summary

Node exposes module.exports. You assign a value to the object and return the value. You add properties to the object and return the object with the properties.