Home > Web Front-end > JS Tutorial > body text

Share an example tutorial on building a vue-cli project.

零下一度
Release: 2017-06-25 09:53:32
Original
1872 people have browsed it

The background mock is implemented in "Adding the Backend Mock Interface to the Project Built by Vue-cli", but the t data of the front-end post must be used in the mock's background interface to use the req receiving data event to obtain the data in the http protocol body. .

req.on('data', function(chunk){  //接收字节数据});

req.end('data', function(){  //转换||处理});

req.error('error', function(e){  //处理错误});
Copy after login

If the front-end needs to use cookies and the back-end needs to read them, then the headers of req must be obtained in the background mock interface, and the cookie string must be obtained from it, and it must be divided by itself Processing and so on.

Of course this is possible, but it is more troublesome. You have to do it yourself from receiving the data to converting it.

The project built by vue-cli uses express as the web framework of node.js, which supports rich middleware.

Corresponding to the above problems, there are body-parser and cookie-parser middleware that can easily extract the data and cookies in the body of the post into req.body and req.cookies objects for human use, which is very convenient.

Install middleware

npm install body-parser --save-dev

npm install cookie-parser --save-dev
Copy after login

Introduce middleware

In build/dev-server. Add middleware require at the end of the header require area in the js file.

  var bodyParser = require('body-parser');  var cookieParser = require('cookie-parser');
Copy after login

Then add the middleware call immediately after var app = express().

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
Copy after login

The two-line calling method of bodyParser is to set the content-type to 'application/json' and 'application/x-www-form-urlencoded' respectively.

After the addition is completed, it is easy to use.

End

The above is the detailed content of Share an example tutorial on building a vue-cli project.. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template