node.js - road express learning (b)

Self roads always so hard, but every time they get close is so happy.

Previous article originally own thing when it comes to built a file modules to do background operations, but later feel the name is not, then re-create the file server to write the background content.

The catalog is roughly like this, the idea is:

api file put some interface request processing

sql inside put some sql statement execution

storing connection configuration server db.js

the entrance is index.js

 

 So celebrate their meal operation,

First, the rookie tutorial to see how express connect to the database: https://www.runoob.com/nodejs/nodejs-mysql.html

Then on the rookie tutorial to see how to write sql statement: https://www.runoob.com/mysql/mysql-insert-query.html

Then how cranky package deal to do.

No one is really too difficult to teach, ultimately, himself a simple process. Later re-learning optimization

Made a query with the added user interface process is difficult, satisfactory results, let us talk about the process of pit encountered.

Online said that with the body-parser can be taken to the front-end content submission, but how I desperately operations or not

const bodyParser = require("body-parser");
const express = require("express");
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

Later, it depends on the data submitted in the past and found that does not seem like I previously submitted to the background. So find some headers where the front end is written

axios.defaults.headers.post["Content-Type"] = "application/json;charset=utf-8";

Suspect may be the cause, and then put that into the above

axios.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";

Ha ha. Sure enough, on it. Well, there is always way more than the problem. Attached below the contents of each js

userApi.js

var models = require("../db");
var express = require("express");
var router = express.Router();
var mysql = require("mysql");
var $sql = require("../sql/sqlMap");
// 连接数据库
var conn = mysql.createConnection(models.mysql);
conn.connect();
var jsonWrite = function(res, ret) {
    if (typeof ret === "undefined") {
        res.json({
            code: "1",
            msg: "operation failed"
        }); 
    } The else { 
        the let Data = {};
         // eslint-disable-Next-NO-Line Constant-for condition Condition 
        Data = { 
            code: 1000 , 
            MSG: "succeed" , 
            List: RET 
        }; 
        res.json (Data ); 
    } 
}; 

// increase user interface 
router.post ( "/ the addUser", (REQ, RES) => {
     var SQL = $ sql.user.addUser;
     var the params = req.body; 
    the console.log (the params) ;
    conn.query(sql, [params.name, params.phone, params.passWord], function(
        err,
        result
    ) {
        if (err) {
            console.log(err);
        }
        if (result) {
            jsonWrite(res, result);
        }
    });
});
//查询用户接口
router.post("/select-user", (req, res) => {
    const sql = $sql.user.selectUser;
    //const params = req.body;
    conn.query(sql, function(err, result) {
        if (err) {
            console.log(err);
        }
        if (result) {
            jsonWrite(res, result);
        }
    });
});
module.exports = router;

sqlMap.js

// sql语句

var sqlMap = {
    // 用户
    user: {
        addUser: "insert into user (name,phone,passWord ) values (?, ?, ?)",
        selectUser: "select * from user"
    }
};

module.exports = sqlMap;

db.js

module.exports = {
    mysql: {
        host: "localhost",
        user: "root",
        password: "root",
        database: "nodestady",
        port: "3306"
    }
};

index.js

the require userApi = const ( "./ API / userApi" );
 // const the require FS = ( "FS"); 
// const = the require path ( "path"); 
const = bodyParser the require ( "body-Parser" ); 
Express const = the require ( "Express" ); 
const App = Express (); 
app.use (bodyParser.json ()); 
app.use (bodyParser.urlencoded ({Extended: to false })); 

// settings allow cross-domain access to the service. 
app.all ( "*", function (REQ, RES, the Next) { 
    res.header ( "access-Control-the Allow-Origin", "*" );
     // access-Control-the Allow-Headers, according F12 to view the browser, the corresponding paste here on the line
    res.header("Access-Control-Allow-Headers", "Content-Type");
    res.header("Access-Control-Allow-Methods", "*");
    res.header("Content-Type", "application/json;charset=utf-8");
    next();
});

// 后端api路由
app.use("/user", userApi);
// 监听端口
app.listen(3000);
console.log("success listen at port:3000......");

Here it can be completed with a simple request returned. But this is not enough, still thinking about how to package the request and the corresponding data, the database how to design, how to package release. . . . . .

 

 

 

 

 

 

 

 

 

Guess you like

Origin www.cnblogs.com/chao202426/p/11976381.html