nodejs request请求接口丨技术开发分享录

nodejs request请求接口

{{ detail.nickname }}

转载 翻译 {{ formatTime(detail.create_time) }} 字数 {{ detail.content && detail.content.length }} 阅读 {{ detail.read_num }} {{ formatTag(v) }}

"request npm文档:https://www.npmjs.com/package/request\n\n`request`依赖安装\n\n```cmd\nnpm install --save request\n```\n\nGET\n\n```\nvar request = require('request');\nrequest('http://www.xxx.com/list', function (error, response, body) {\n  if (!error && response.statusCode == 200) {\n    console.log(body) // Show the HTML for the baidu homepage.\n  }\n})\n```\n\nGET(**qs**)\n\n```\nrequest({\n    strictSSL: false, // 默认true,跳过https签名证书验证\n    url: url,\n    method: \"GET\", // 默认GET,可以不设\n    headers: {\n        \"content-type\": \"application/json\",\n    },\n    qs: {page: 1}\n}, function(error, response, body) {\n    if (!error && response.statusCode == 200) {\n    }\n})\n```\n\nPOST(**application/json**)\n\n```\nrequest({\n    url: url,\n    method: \"POST\",\n    headers: {\n        \"content-type\": \"application/json\",\n    },\n    body: JSON.stringify({keywords: 'vue'})\n}, function(error, response, body) {\n    if (!error && response.statusCode == 200) {\n    }\n})\n```\n\n或\n\n```\nrequest({\n    url: url,\n    method: \"POST\",\n    headers: {\n        \"content-type\": \"application/json\",\n    },\n    json: true,\n    body: {keywords: 'vue'}\n}, function(error, response, body) {\n    if (!error && response.statusCode == 200) {\n    }\n})\n```\n\nPOST(**application/x-www-form-urlencoded**)\n\n```\nrequest.post({url:'http://service.com/upload', form: {keywords: 'vue'}}, function(error, response, body) {\n    if (!error && response.statusCode == 200) {\n    }\n})\n```\n\nPOST(**multipart/form-data**)\n\n```\nvar formData = {\n    // Pass a simple key-value pair\n    my_field: 'my_value',\n    // Pass data via Buffers\n    my_buffer: new Buffer([1, 2, 3]),\n    // Pass data via Streams\n    my_file: fs.createReadStream(__dirname + '/unicycle.jpg'),\n};\nrequest.post({url:'http://service.com/upload', formData: formData}, function (error, response, body) {  \n    if (!error && response.statusCode == 200) {\n    }\n})\n```\n\n在路由中使用 api/index.js\n\n```\nvar express = require('express');\nvar router = express.Router();\nvar request = require('request');\n\n// 获取列表\nrouter.post('/list', function(req, res, next) {\n   request({\n        url: 'http://www.xxx.com/list',\n        method: \"POST\",\n        headers: {\n            \"content-type\": \"application/json\",\n        },\n        body: JSON.stringify({keywords: 'vue'})\n    }, function(error, response, body) {\n        if (!error && response.statusCode == 200) {\n        \tres.send(body);\n        }\n    }); \n});\n```\n\n参考链接:\n\n- https://blog.csdn.net/dreamer2020/article/details/52074516"
PS:写作不易,如要转裁,请标明转载出处。

如果此篇对您有帮助,可小额赞助,以兹鼓励!

猜你想看