node.js学习(七、express框架创建api接口)
2017-03-14 19:54
726 查看
根据官方文档,用如下方式构造请求:
在get的路径参数中填写请求路径,其中请求需要的参数用/:参数名表示。如上req代表请求数据,res代表服务器返回给浏览器的数据。那么服务器如何获取请求的参数呢,不妨打印一下req对象。上传代码至服务器,node app.js运行。浏览器请求http://goodboy.ren:3000/login/name/123,返回get it代表请求成功。此时查看服务器,打印如下一段:
这里即为请求大全部信息,仔细查找发现一行
params: { username: ‘name’, password: ‘123’ }
这就是我们要或取的值,由此可知get请求的参数是放在params属性中,通过req.params即可获取参数对象。
通过以下代码测试一下:
执行代码再次请求,返回get userinfo username=name,password=123。说明获取到了所以的请求参数。实际开发过程中,还须对相应的参数进行处理再返回需要的数据。后续章节会进行讲述。
以上为get请求方式获取数据。当我们需要发送大量数据时,不得不使用post方式提交数据。那么post方法如何获得请求参数,复制开始的代码,修改一下,如下:
执行以上代码,用浏览器打开http://www.atool.org/httptest.php
按上图填写后点击发生请求按钮,返回post success。
通过打印日志发现,请求参数没有在打印的日志中。
这时我们需要借助第三方模块body-parser,git地址为https://github.com/expressjs/body-parser
里面有详细的使用说明,按照说明中的例子修改后完整代码如下:
执行后报错
Error: Cannot find module ‘body-parser’
at Function.Module._resolveFilename (module.js:325:15)
at Function.Module._load (module.js:276:25)
at Module.require (module.js:353:17)
at require (internal/module.js:12:17)
at Object. (/data/nodeweb/app.js:4:18)
at Module._compile (module.js:409:26)
at Object.Module._extensions..js (module.js:416:10)
at Module.load (module.js:343:32)
at Function.Module._load (module.js:300:12)
at Function.Module.runMain (module.js:441:10)
以上错误代表没有下载安装body-parser包,使用npm install -g body-parser 命令安装。安装完成后,执行node app.js。再次通过浏览器请求,获得返回结果。
大功告成。下篇记录如何使用mysql记录请求数据或者查询数据。
app.get("/login/:username/:password",function (req, res) { console.log(req); res.send("get it"); });
在get的路径参数中填写请求路径,其中请求需要的参数用/:参数名表示。如上req代表请求数据,res代表服务器返回给浏览器的数据。那么服务器如何获取请求的参数呢,不妨打印一下req对象。上传代码至服务器,node app.js运行。浏览器请求http://goodboy.ren:3000/login/name/123,返回get it代表请求成功。此时查看服务器,打印如下一段:
IncomingMessage { _readableState: ReadableState { objectMode: false, highWaterMark: 16384, buffer: [], length: 0, pipes: null, pipesCount: 0, flowing: null, ended: false, endEmitted: false, reading: false, sync: true, needReadable: false, emittedReadable: false, readableListening: false, resumeScheduled: false, defaultEncoding: 'utf8', ranOut: false, awaitDrain: 0, readingMore: false, decoder: null, encoding: null }, readable: true, domain: null, _events: {}, _eventsCount: 0, _maxListeners: undefined, socket: Socket { _connecting: false, _hadError: false, _handle: TCP { _externalStream: {}, fd: 12, reading: true, owner: [Circular], onread: [Function: onread], onconnection: null, writeQueueSize: 0 }, _parent: null, _host: null, _readableState: ReadableState { objectMode: false, highWaterMark: 16384, 4000 buffer: [], length: 0, pipes: null, pipesCount: 0, flowing: true, ended: false, endEmitted: false, reading: true, sync: false, needReadable: true, emittedReadable: false, readableListening: false, resumeScheduled: false, defaultEncoding: 'utf8', ranOut: false, awaitDrain: 0, readingMore: false, decoder: null, encoding: null }, readable: true, domain: null, _events: { end: [Object], finish: [Function: onSocketFinish], _socketEnd: [Function: onSocketEnd], drain: [Object], timeout: [Function], error: [Function: socketOnError], close: [Object], data: [Function: socketOnData], resume: [Function: onSocketResume], pause: [Function: onSocketPause] }, _eventsCount: 10, _maxListeners: undefined, _writableState: WritableState { objectMode: false, highWaterMark: 16384, needDrain: false, ending: false, ended: false, finished: false, decodeStrings: false, defaultEncoding: 'utf8', length: 0, writing: false, corked: 0, sync: true, bufferProcessing: false, onwrite: [Function], writecb: null, writelen: 0, bufferedRequest: null, lastBufferedRequest: null, pendingcb: 0, prefinished: false, errorEmitted: false, bufferedRequestCount: 0, corkedRequestsFree: [Object] }, writable: true, allowHalfOpen: true, destroyed: false, bytesRead: 0, _bytesDispatched: 0, _sockname: null, _pendingData: null, _pendingEncoding: '', server: Server { domain: null, _events: [Object], _eventsCount: 3, _maxListeners: undefined, _connections: 1, _handle: [Object], _usingSlaves: false, _slaves: [], _unref: false, allowHalfOpen: true, pauseOnConnect: false, httpAllowHalfOpen: false, timeout: 120000, _pendingResponseData: 0, _connectionKey: '4:0.0.0.0:3000' }, _server: Server { domain: null, _events: [Object], _eventsCount: 3, _maxListeners: undefined, _connections: 1, _handle: [Object], _usingSlaves: false, _slaves: [], _unref: false, allowHalfOpen: true, pauseOnConnect: false, httpAllowHalfOpen: false, timeout: 120000, _pendingResponseData: 0, _connectionKey: '4:0.0.0.0:3000' }, _idleTimeout: 120000, _idleNext: { _idleNext: [Circular], _idlePrev: [Circular] }, _idlePrev: { _idleNext: [Circular], _idlePrev: [Circular] }, _idleStart: 7105, parser: HTTPParser { '0': [Function: parserOnHeaders], '1': [Function: parserOnHeadersComplete], '2': [Function: parserOnBody], '3': [Function: parserOnMessageComplete], '4': [Function: onParserExecute], _headers: [], _url: '', _consumed: true, socket: [Circular], incoming: [Circular], outgoing: null, maxHeaderPairs: 2000, onIncoming: [Function: parserOnIncoming] }, on: [Function: socketOnWrap], _paused: false, read: [Function], _consuming: true, _httpMessage: ServerResponse { domain: null, _events: [Object], _eventsCount: 1, _maxListeners: undefined, output: [], outputEncodings: [], outputCallbacks: [], outputSize: 0, writable: true, _last: false, chunkedEncoding: false, shouldKeepAlive: true, useChunkedEncodingByDefault: true, sendDate: true, _removedHeader: {}, _contentLength: null, _hasBody: true, _trailer: '', finished: false, _headerSent: false, socket: [Circular], connection: [Circular], _header: null, _headers: [Object], _headerNames: [Object], _onPendingData: [Function: updateOutgoingData], req: [Circular], locals: {} } }, connection: Socket { _connecting: false, _hadError: false, _handle: TCP { _externalStream: {}, fd: 12, reading: true, owner: [Circular], onread: [Function: onread], onconnection: null, writeQueueSize: 0 }, _parent: null, _host: null, _readableState: ReadableState { objectMode: false, highWaterMark: 16384, buffer: [], length: 0, pipes: null, pipesCount: 0, flowing: true, ended: false, endEmitted: false, reading: true, sync: false, needReadable: true, emittedReadable: false, readableListening: false, resumeScheduled: false, defaultEncoding: 'utf8', ranOut: false, awaitDrain: 0, readingMore: false, decoder: null, encoding: null }, readable: true, domain: null, _events: { end: [Object], finish: [Function: onSocketFinish], _socketEnd: [Function: onSocketEnd], drain: [Object], timeout: [Function], error: [Function: socketOnError], close: [Object], data: [Function: socketOnData], resume: [Function: onSocketResume], pause: [Function: onSocketPause] }, _eventsCount: 10, _maxListeners: undefined, _writableState: WritableState { objectMode: false, highWaterMark: 16384, needDrain: false, ending: false, ended: false, finished: false, decodeStrings: false, defaultEncoding: 'utf8', length: 0, writing: false, corked: 0, sync: true, bufferProcessing: false, onwrite: [Function], writecb: null, writelen: 0, bufferedRequest: null, lastBufferedRequest: null, pendingcb: 0, prefinished: false, errorEmitted: false, bufferedRequestCount: 0, corkedRequestsFree: [Object] }, writable: true, allowHalfOpen: true, destroyed: false, bytesRead: 0, _bytesDispatched: 0, _sockname: null, _pendingData: null, _pendingEncoding: '', server: Server { domain: null, _events: [Object], _eventsCount: 3, _maxListeners: undefined, _connections: 1, _handle: [Object], _usingSlaves: false, _slaves: [], _unref: false, allowHalfOpen: true, pauseOnConnect: false, httpAllowHalfOpen: false, timeout: 120000, _pendingResponseData: 0, _connectionKey: '4:0.0.0.0:3000' }, _server: Server { domain: null, _events: [Object], _eventsCount: 3, _maxListeners: undefined, _connections: 1, _handle: [Object], _usingSlaves: false, _slaves: [], _unref: false, allowHalfOpen: true, pauseOnConnect: false, httpAllowHalfOpen: false, timeout: 120000, _pendingResponseData: 0, _connectionKey: '4:0.0.0.0:3000' }, _idleTimeout: 120000, _idleNext: { _idleNext: [Circular], _idlePrev: [Circular] }, _idlePrev: { _idleNext: [Circular], _idlePrev: [Circular] }, _idleStart: 7105, parser: HTTPParser { '0': [Function: parserOnHeaders], '1': [Function: parserOnHeadersComplete], '2': [Function: parserOnBody], '3': [Function: parserOnMessageComplete], '4': [Function: onParserExecute], _headers: [], _url: '', _consumed: true, f459 socket: [Circular], incoming: [Circular], outgoing: null, maxHeaderPairs: 2000, onIncoming: [Function: parserOnIncoming] }, on: [Function: socketOnWrap], _paused: false, read: [Function], _consuming: true, _httpMessage: ServerResponse { domain: null, _events: [Object], _eventsCount: 1, _maxListeners: undefined, output: [], outputEncodings: [], outputCallbacks: [], outputSize: 0, writable: true, _last: false, chunkedEncoding: false, shouldKeepAlive: true, useChunkedEncodingByDefault: true, sendDate: true, _removedHeader: {}, _contentLength: null, _hasBody: true, _trailer: '', finished: false, _headerSent: false, socket: [Circular], connection: [Circular], _header: null, _headers: [Object], _headerNames: [Object], _onPendingData: [Function: updateOutgoingData], req: [Circular], locals: {} } }, httpVersionMajor: 1, httpVersionMinor: 1, httpVersion: '1.1', complete: false, headers: { host: 'goodboy.ren:3000', connection: 'keep-alive', 'cache-control': 'max-age=0', accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8', 'upgrade-insecure-requests': '1', 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36', 'accept-encoding': 'gzip, deflate, sdch', 'accept-language': 'zh-CN,zh;q=0.8' }, rawHeaders: [ 'Host', 'goodboy.ren:3000', 'Connection', 'keep-alive', 'Cache-Control', 'max-age=0', 'Accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8', 'Upgrade-Insecure-Requests', '1', 'User-Agent', 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36', 'Accept-Encoding', 'gzip, deflate, sdch', 'Accept-Language', 'zh-CN,zh;q=0.8' ], trailers: {}, rawTrailers: [], upgrade: false, url: '/login/name/123', method: 'GET', statusCode: null, statusMessage: null, client: Socket { _connecting: false, _hadError: false, _handle: TCP { _externalStream: {}, fd: 12, reading: true, owner: [Circular], onread: [Function: onread], onconnection: null, writeQueueSize: 0 }, _parent: null, _host: null, _readableState: ReadableState { objectMode: false, highWaterMark: 16384, buffer: [], length: 0, pipes: null, pipesCount: 0, flowing: true, ended: false, endEmitted: false, reading: true, sync: false, needReadable: true, emittedReadable: false, readableListening: false, resumeScheduled: false, defaultEncoding: 'utf8', ranOut: false, awaitDrain: 0, readingMore: false, decoder: null, encoding: null }, readable: true, domain: null, _events: { end: [Object], finish: [Function: onSocketFinish], _socketEnd: [Function: onSocketEnd], drain: [Object], timeout: [Function], error: [Function: socketOnError], close: [Object], data: [Function: socketOnData], resume: [Function: onSocketResume], pause: [Function: onSocketPause] }, _eventsCount: 10, _maxListeners: undefined, _writableState: WritableState { objectMode: false, highWaterMark: 16384, needDrain: false, ending: false, ended: false, finished: false, decodeStrings: false, defaultEncoding: 'utf8', length: 0, writing: false, corked: 0, sync: true, bufferProcessing: false, onwrite: [Function], writecb: null, writelen: 0, bufferedRequest: null, lastBufferedRequest: null, pendingcb: 0, prefinished: false, errorEmitted: false, bufferedRequestCount: 0, corkedRequestsFree: [Object] }, writable: true, allowHalfOpen: true, destroyed: false, bytesRead: 0, _bytesDispatched: 0, _sockname: null, _pendingData: null, _pendingEncoding: '', server: Server { domain: null, _events: [Object], _eventsCount: 3, _maxListeners: undefined, _connections: 1, _handle: [Object], _usingSlaves: false, _slaves: [], _unref: false, allowHalfOpen: true, pauseOnConnect: false, httpAllowHalfOpen: false, timeout: 120000, _pendingResponseData: 0, _connectionKey: '4:0.0.0.0:3000' }, _server: Server { domain: null, _events: [Object], _eventsCount: 3, _maxListeners: undefined, _connections: 1, _handle: [Object], _usingSlaves: false, _slaves: [], _unref: false, allowHalfOpen: true, pauseOnConnect: false, httpAllowHalfOpen: false, timeout: 120000, _pendingResponseData: 0, _connectionKey: '4:0.0.0.0:3000' }, _idleTimeout: 120000, _idleNext: { _idleNext: [Circular], _idlePrev: [Circular] }, _idlePrev: { _idleNext: [Circular], _idlePrev: [Circular] }, _idleStart: 7105, parser: HTTPParser { '0': [Function: parserOnHeaders], '1': [Function: parserOnHeadersComplete], '2': [Function: parserOnBody], '3': [Function: parserOnMessageComplete], '4': [Function: onParserExecute], _headers: [], _url: '', _consumed: true, socket: [Circular], incoming: [Circular], outgoing: null, maxHeaderPairs: 2000, onIncoming: [Function: parserOnIncoming] }, on: [Function: socketOnWrap], _paused: false, read: [Function], _consuming: true, _httpMessage: ServerResponse { domain: null, _events: [Object], _eventsCount: 1, _maxListeners: undefined, output: [], outputEncodings: [], outputCallbacks: [], outputSize: 0, writable: true, _last: false, chunkedEncoding: false, shouldKeepAlive: true, useChunkedEncodingByDefault: true, sendDate: true, _removedHeader: {}, _contentLength: null, _hasBody: true, _trailer: '', finished: false, _headerSent: false, socket: [Circular], connection: [Circular], _header: null, _headers: [Object], _headerNames: [Object], _onPendingData: [Function: updateOutgoingData], req: [Circular], locals: {} } }, _consuming: false, _dumped: false, next: [Function: next], baseUrl: '', originalUrl: '/login/name/123', _parsedUrl: Url { protocol: null, slashes: null, auth: null, host: null, port: null, hostname: null, hash: null, search: null, query: null, pathname: '/login/name/123', path: '/login/name/123', href: '/login/name/123', _raw: '/login/name/123' }, params: { username: 'name', password: '123' }, query: {}, res: ServerResponse { domain: null, _events: { finish: [Function: resOnFinish] }, _eventsCount: 1, _maxListeners: undefined, output: [], outputEncodings: [], outputCallbacks: [], outputSize: 0, writable: true, _last: false, chunkedEncoding: false, shouldKeepAlive: true, useChunkedEncodingByDefault: true, sendDate: true, _removedHeader: {}, _contentLength: null, _hasBody: true, _trailer: '', finished: false, _headerSent: false, socket: Socket { _connecting: false, _hadError: false, _handle: [Object], _parent: null, _host: null, _readableState: [Object], readable: true, domain: null, _events: [Object], _eventsCount: 10, _maxListeners: undefined, _writableState: [Object], writable: true, allowHalfOpen: true, destroyed: false, bytesRead: 0, _bytesDispatched: 0, _sockname: null, _pendingData: null, _pendingEncoding: '', server: [Object], _server: [Object], _idleTimeout: 120000, _idleNext: [Object], _idlePrev: [Object], _idleStart: 7105, parser: [Object], on: [Function: socketOnWrap], _paused: false, read: [Function], _consuming: true, _httpMessage: [Circular] }, connection: Socket { _connecting: false, _hadError: false, _handle: [Object], _parent: null, _host: null, _readableState: [Object], readable: true, domain: null, _events: [Object], _eventsCount: 10, _maxListeners: undefined, _writableState: [Object], writable: true, allowHalfOpen: true, destroyed: false, bytesRead: 0, _bytesDispatched: 0, _sockname: null, _pendingData: null, _pendingEncoding: '', server: [Object], _server: [Object], _idleTimeout: 120000, _idleNext: [Object], _idlePrev: [Object], _idleStart: 7105, parser: [Object], on: [Function: socketOnWrap], _paused: false, read: [Function], _consuming: true, _httpMessage: [Circular] }, _header: null, _headers: { 'x-powered-by': 'Express' }, _headerNames: { 'x-powered-by': 'X-Powered-By' }, _onPendingData: [Function: updateOutgoingData], req: [Circular], locals: {} }, route: Route { path: '/login/:username/:password', stack: [ [Object] ], methods: { get: true } } }
这里即为请求大全部信息,仔细查找发现一行
params: { username: ‘name’, password: ‘123’ }
这就是我们要或取的值,由此可知get请求的参数是放在params属性中,通过req.params即可获取参数对象。
通过以下代码测试一下:
app.get("/login/:username/:password",function (req, res) { var user=req.params; var ret="get userinfo username="+user.username+",password="+user.password; res.send(ret); });
执行代码再次请求,返回get userinfo username=name,password=123。说明获取到了所以的请求参数。实际开发过程中,还须对相应的参数进行处理再返回需要的数据。后续章节会进行讲述。
以上为get请求方式获取数据。当我们需要发送大量数据时,不得不使用post方式提交数据。那么post方法如何获得请求参数,复制开始的代码,修改一下,如下:
app.get("/login/:username/:password",function (req, res) { var user=req.params; var ret="get userinfo username="+user.username+",password="+user.password; res.send(ret); }); app.post("/login",function (req, res) { console.log(req); res.send("post success"); });
执行以上代码,用浏览器打开http://www.atool.org/httptest.php
按上图填写后点击发生请求按钮,返回post success。
通过打印日志发现,请求参数没有在打印的日志中。
这时我们需要借助第三方模块body-parser,git地址为https://github.com/expressjs/body-parser
里面有详细的使用说明,按照说明中的例子修改后完整代码如下:
var express=require('express'); var app=express(); var bodyParser = require('body-parser') // parse application/x-www-form-urlencoded app.use(bodyParser.urlencoded({ extended: false })) // parse application/json app.use(bodyParser.json()) app.get("/sayhello",function (req, res) { res.send('Hello World!'); }); app.get("/login/:username/:password",function (req, res) { var user=req.params; var ret="get userinfo username="+user.username+",password="+user.password; res.send(ret); }); app.post("/login",function (req, res) { var user=req.body; console.log(user); var ret="get userinfo username="+user.username+",password="+user.password; res.send(ret); }); var server = app.listen(3000);
执行后报错
Error: Cannot find module ‘body-parser’
at Function.Module._resolveFilename (module.js:325:15)
at Function.Module._load (module.js:276:25)
at Module.require (module.js:353:17)
at require (internal/module.js:12:17)
at Object. (/data/nodeweb/app.js:4:18)
at Module._compile (module.js:409:26)
at Object.Module._extensions..js (module.js:416:10)
at Module.load (module.js:343:32)
at Function.Module._load (module.js:300:12)
at Function.Module.runMain (module.js:441:10)
以上错误代表没有下载安装body-parser包,使用npm install -g body-parser 命令安装。安装完成后,执行node app.js。再次通过浏览器请求,获得返回结果。
大功告成。下篇记录如何使用mysql记录请求数据或者查询数据。
相关文章推荐
- 从零开始学习Node.js系列教程之基于connect和express框架的多页面实现数学运算示例
- node.js 和 express 框架学习笔记(1)
- node.js Express框架学习笔记
- node.js学习笔记(3)--Express创建的项目分析
- Node.js Express 框架学习
- Node.js Express 框架学习
- node.js学习--创建一个express服务
- Node.js学习(2) Express创建简单网站过程
- nodejs express 框架解密2-如何创建一个app
- node.js学习(六、express创建web服务器)
- node.js 和 express 框架学习笔记(2)
- Node.js Express 框架学习
- node.js 和 express 框架学习笔记(3)
- Node.js Express 框架学习
- nodejs express 框架解密5-视图
- Node.js中的express框架获取http参数
- node.js-express框架的初步使用。
- Node.js学习笔记6【express--hello world】
- Node.js利用Express框架搭建小型网站(下)
- node.js安装及Express框架简介