首页 > 解决方案 > 如何使用 Node.JS 向 Ghostbin 发出 POST 请求?

问题描述

我正在尝试通过 Node.JS 及其NPM 模块向Ghostbin发送 POST 请求。request这是我的代码的样子:

尝试1:

reqest.post({
   url: "https://ghostbin.com/paste/new",
   text: "test post"
}, function (err, res, body) {
   console.log(res)
})

尝试2:

reqest.post({
   url: "https://ghostbin.com/paste/new",
   text: "test post",
   headers: {
      "Content-Type": "application/x-www-form-urlencoded",
      "Content-Length": 9
   }
}, function (err, res, body) {
   console.log(res)
})

尝试 3:

reqest.post("https://ghostbin.com/paste/new", {form: {text: "test post"}}, function (err, res, body) {
   console.log(res)
})

所有这些尝试最终都记录了:

<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">\n<html><head>\n<title>406 Not Acceptable</title>\n</head><body>\n<h1>Not Acceptable</h1>\n<p>An appropriate representation of the requested resource /paste/new could not be found on this server.</p>\n<hr>\n<address>Apache/2.4.18 (Ubuntu) Server at ghostbin.com Port 443</address>\n</body></html>

request关于库或Ghostbin API 的文档,我有什么遗漏吗?

标签: javascriptnode.jspostrequesthttprequest

解决方案


您几乎是对的,但是您需要将数据传递到form密钥中(就像您在 #3 中所做的那样)并user-agent按照 api 中的说明传递标头

reqest.post({
   url: "https://ghostbin.com/paste/new",
   form: {
     text: "test post"
   },
   headers: {
      'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36'
   }
}, function (err, res, body) {
   console.log(res)
})

推荐阅读