24

cURL简介:高级程序员都在用的工具

 3 years ago
source link: http://developer.51cto.com/art/202010/628151.htm
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

在本教程中,我们介绍cURL的基本选项,并通过示例介绍如何使用它们,然后我们开发了一个带有三个端点的Node/Express服务器,以演示如何使用本文介绍的cURL选项对服务器执行cURL的GET/POST请求。

与cURL一起使用的选项很多,我们在此介绍的是可用于快速测试API端点的基本选项。

462cc3f052782ef2bd9879ee5aee0d8d.png-wh_651x-s_739549938.png

介绍

cURL是一种用于从服务器传输数据或向服务器传输数据的传输工具。它支持各种互联网传输协议,包括:

  • DICT
  • FILE
  • FTP, FTPS
  • GOPHER
  • HTTP, HTTPS
  • IMAP, IMAPS
  • LDAP, LDAPS
  • POP3, POP3S
  • RTMP, RTSP
  • SCP, SFTP
  • SMB, SMBS
  • SMTP, SMTPS
  • TELNET and TFTP

我们可以使用cURL执行一些有用的技巧,如代理支持、用户身份验证、FTP上传、HTTP post、SSL连接、cookie、文件传输恢复、Metalink等等。

cURL是在命令行中使用的,在软件开发过程中,它主要是用来快速测试API的。当我想在Node.js服务器中测试我所有的API时,我个人使用cURL。对于开发者来说,这是一个非常方便的工具。

Postman很酷,但是cURL非常酷。

– Chidume Nnamdi

在本文中,我们将介绍基本的cURL函数和选项。我们还将学习如何使用cURL在API端点上执行GET,POST请求。

cURL选项

(1) --request 或者 -X

—request 和 -X 指定与HTTP服务器通信时可以使用的自定义请求方法,将使用指定的请求方法代替其他方法(默认为GET)。

要执行POST请求:

curl --request POST 

要执行GET请求:

curl --request GET 

(2) --url

这指定了我们将获取或传输数据的URL,当你想在配置文件中指定URL时,这个选项非常方便。

如果给定的URL缺少scheme name(例如“http://””或“ftp://””等),则cURL将基于主机进行猜测。

如果最外面的子域名与DICT,FTP,IMAP,LDAP,POP3或SMTP匹配,则将使用该协议。否则,将使用HTTP。

例如,如果你想在本地服务器上的 localhost:3000 上执行GET请求,则需要将 --url 设置为 localhost:3000:

curl --request GET \ 
    --url http://localhost:3000 

要在同一URL上执行POST:

curl --request POST \ 
    --url http://localhost:3000 

注意:反斜杠 \ 用于分隔cURL中的选项。

对于外部API,还是一样。

假设你要从https://moviesdb.com/movies/all获取电影列表。

curl --request GET \ 
    --url https://moviesdb.com/movies/all 

moviedb 中所有电影的列表都将被获取并打印。

(3) --header 或者 -H

这个选项用于设置请求的头信息。

当向服务器发送HTTP时,在请求中包含的额外头。你可以指定任意数量的额外头。请注意,如果你要添加一个自定义的头文件,而这个头文件的名字与 curl 内部使用的头文件相同,那么你在外部设置的头将被用来代替内部头。

这反映了我们在正常编程中的做法,特别是在JavaScript中使用 XMLHttpRequest:

const xhttp = new XMLHttpRequest() 
xhttp.setHeader("Content-Type", "application/json") 

头信息用于向Web服务器传达传入的数据类型,或期望的数据类型,发送的数据类型应与标头中指定的类型相同。

我们可以使用头文件来获得CORS权限,甚至可以获得某些类型的请求方法的权限。我们可以用头文件做的事情有很多。

因此,在cURL中,我们可以使用 —header 选项设置标头:

curl --request POST \ 
  --url http://localhost:5000/api/user \  --header 'content-type: application/json' 

这里,我们正在向http://localhost:5000/api/user 端点发出 POST 请求,并通过 --header content-type: application/json’ 告诉服务器我们要发送的数据是 JSON 数据类型。

(4) --data 或者 -d

此选项用于将数据发送到HTTP服务器,这主要是在POST请求中使用,因为我们将数据发送到我们要添加到数据库的服务器。因此,在cURL中,我们可以通过设置 —data 选项将数据指定为POST。

在POST请求中向HTTP服务器发送指定的数据,就像浏览器在用户填写HTML表格并按下提交按钮时一样。

这是一个例子:

curl --request POST \ 
  --url http://localhost:5000 \ 
  --header 'content-type: application/json' \ 
  --data '{"name":"Arrow","description":"bad movie","rating":"7.0","image":"michaeljackson.png"}' 

在这里,我们正在执行对 http://localhost:5000端点的POST请求。

我们在 —data 选项中设置了要发送到服务器的数据,即:

'{"name":"Arrow","description":"bad movie","rating":"7.0","image":"michaeljackson.png”} 

在Node.js / Express.js中使用cURL

让我们看看如何设置Node.js / Express.js服务器并使用cURL测试端点:

// server.js 
const express = require("express") 
const cors = require('cors') 
const bodyParser = require('body-parser') 
const helmet = require('helmet') 
const app = express()let port = 5000 || process.env.PORT 
/** 设置中间件 */app.use(cors())app.use(bodyParser.json({limit: '50mb'})) 
app.use(helmet())let users = []let currId  Date.now()app.get("api/user/:id", (req, res, next) => { 
  const userId = req.params.id  const usersusers = users.filter(user => user.id === userId)  if(users.length > 0) 
    res.send({ user: users[0] }) 
  else 
    res.send({mesg: "No user found."}) 
  next() 
})app.get("api/users", (req, res, next) => { 
  res.send({ users })  next() 
})app.post("api/user", (req, res, next) => { 
  let bdy = req.body  bdy = { id: ++currId, ...bdy }  users.push(bdy)  res.send({ user: bdy })  next()     
})/** 启动服务器 */app.listen(port, () => {  console.log(`Server started at port: ${port}`); 
}); 

我们在这里有一些小的API端点:

  • GEt api/users
  • GET api/user/:id
  • POST api/user它通过其 id 提取所有用户(特定用户),并可以添加新用户。

启动服务器:

node server.js 
Server started at port: 5000 

现在,要在 api/user 上执行POST请求,我们将 —url 设置为 http://localhost:5000/api/user,并将 --request 设置为POST,将 --header 设置为 content-type:application/json。

我们要添加用户:

name: "Chidume", 
age: 28 

因此数据将为 '{"name": "Chidume", "age": "28"}'

因此,cURL命令将是:

curl --request POST \ 
  --url http://localhost:5000/api/user \ 
  --header 'content-type: application/json' \ 
  --data '{"name": "Chidume", "age": "28"}' 
{ id: 5122435464, name: "Chidume", age: 28 } 

我们从服务器上看到了结果:将用户及其 id 添加到数据库中。

让我们添加另一个用户:

curl --request POST \ 
  --url http://localhost:5000/api/user \ 
  --header 'content-type: application/json' \ 
  --data '{"name": "Nnamdi", "age": "21"}' 
{ id: 5122435465, name: "Nnamdi", age: 21 } 

我们添加了另一个用户“Nnamdi”,我们可以看到服务器的 id 及其结果。

现在,让我们通过 api/user/:id 查询“ Chidume”。在这里 :id 将是 id 5122435464。因此cURL将是:

curl --request GET \ 
  --url http://localhost:5000/api/user/5122435464 
{ user: { id: 5122435464, name: "Chidume", age: 28 } } 

服务器的结果返回 id 为5122435464的用户,即“Chidume”。

现在让我们查询一个不存在的用户:

curl --request GET \ 
  --url http://localhost:5000/api/user/2000000000 
{ mesg: "No user found." } 

这是当我们遇到不存在的用户时服务器上返回的结果。

现在,让我们查询所有用户:

curl --request GET \ 
  --url http://localhost:5000/api/users 
{ users: [ { id: 5122435465, name: "Nnamdi", age: 21 }, { id: 5122435464, name: "Chidume", age: 28 } ] } 

如你所见,将返回服务器中的所有用户。

【责任编辑:赵宁宁 TEL:(010)68476606】


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK