我正在执行此发布请求,得到了很大的答复,但没有包含密钥,这是密钥的范例:{"key":"qurixofafa"}
。如何访问此JSON对象?
const axios = require('axios')
axios.post('http://hastebin.com/documents', {
payload: 'test'
})
.then((res) => {
console.log(`statusCode: ${res.statusCode}`)
console.log(res)
})
.catch((error) => {
console.error(error)
})
这是我从上面的代码中得到的响应。我可能已经略过了,但我不认为关键在于此响应。该请求进行得很好,但是我没有获得网站本身上提供的JSON对象。这可能是问题的一部分,但我不确定GET /documents HTTP/1.1\r\nAccept: application/json, text/plain, */*\r\nUser-Agent: axios/0.19.0\r\nHost: hastebin.com\r\nConnection: close\r\n\r\n
{ status: 200,
statusText: 'OK',
headers:
{ date: 'Sun, 13 Oct 2019 07:23:09 GMT',
'content-type': 'text/html',
'transfer-encoding': 'chunked',
connection: 'close',
'set-cookie':
[ '__cfduid=dbd454f479...; expires=Mon, 12-Oct-20 07:23:09 GMT; path=/; domain=.hastebin.com; HttpOnly' ],
'x-ratelimit-limit': '500',
'x-ratelimit-remaining': '499',
'cache-control': 'public, max-age=600',
'last-modified': 'Fri, 05 Apr 2019 21:32:57 GMT',
via: '1.1 vegur',
'cf-cache-status': 'DYNAMIC',
'expect-ct':
'max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct"',
server: 'cloudflare',
'cf-ray': '524f9107e890d529-MIA' },
config:
{ url: 'http://hastebin.com/documents',
method: 'post',
data: '{"payload":"test"}',
headers:
{ Accept: 'application/json, text/plain, */*',
'User-Agent': 'axios/0.19.0' },
transformRequest: [ [Function: transformRequest] ],
transformResponse: [ [Function: transformResponse] ],
timeout: 0,
adapter: [Function: httpAdapter],
xsrfCookieName: 'XSRF-TOKEN',
xsrfHeaderName: 'X-XSRF-TOKEN',
maxContentLength: -1,
validateStatus: [Function: validateStatus] },
request:
ClientRequest {
_events:
[Object: null prototype] {
socket: [Function],
abort: [Function],
aborted: [Function],
error: [Function],
timeout: [Function],
prefinish: [Function: requestOnPrefinish] },
_eventsCount: 6,
_maxListeners: undefined,
output: [],
outputEncodings: [],
outputCallbacks: [],
outputSize: 0,
writable: true,
_last: true,
chunkedEncoding: false,
shouldKeepAlive: false,
useChunkedEncodingByDefault: false,
sendDate: false,
_removedConnection: false,
_removedContLen: false,
_removedTE: false,
_contentLength: 0,
_hasBody: true,
_trailer: '',
finished: true,
_headerSent: true,
socket:
TLSSocket {
_tlsOptions: [Object],
_secureEstablished: true,
_securePending: false,
_newSessionPending: false,
_controlReleased: true,
_SNICallback: null,
servername: 'hastebin.com',
alpnProtocol: false,
authorized: true,
authorizationError: null,
encrypted: true,
_events: [Object],
_eventsCount: 8,
connecting: false,
_hadError: false,
_handle: [TLSWrap],
_parent: null,
_host: 'hastebin.com',
_readableState: [ReadableState],
readable: true,
_maxListeners: undefined,
_writableState: [WritableState],
writable: false,
allowHalfOpen: false,
_sockname: null,
_pendingData: null,
_pendingEncoding: '',
server: undefined,
_server: null,
ssl: [TLSWrap],
_requestCert: true,
_rejectUnauthorized: true,
parser: null,
_httpMessage: [Circular],
[Symbol(res)]: [TLSWrap],
[Symbol(asyncId)]: 14,
[Symbol(lastWriteQueueSize)]: 0,
[Symbol(timeout)]: null,
[Symbol(kBytesRead)]: 0,
[Symbol(kBytesWritten)]: 0,
[Symbol(connect-options)]: [Object] },
connection:
TLSSocket {
_tlsOptions: [Object],
_secureEstablished: true,
_securePending: false,
_newSessionPending: false,
_controlReleased: true,
_SNICallback: null,
servername: 'hastebin.com',
alpnProtocol: false,
authorized: true,
authorizationError: null,
encrypted: true,
_events: [Object],
_eventsCount: 8,
connecting: false,
_hadError: false,
_handle: [TLSWrap],
_parent: null,
_host: 'hastebin.com',
_readableState: [ReadableState],
readable: true,
_maxListeners: undefined,
_writableState: [WritableState],
writable: false,
allowHalfOpen: false,
_sockname: null,
_pendingData: null,
_pendingEncoding: '',
server: undefined,
_server: null,
ssl: [TLSWrap],
_requestCert: true,
_rejectUnauthorized: true,
parser: null,
_httpMessage: [Circular],
[Symbol(res)]: [TLSWrap],
[Symbol(asyncId)]: 14,
[Symbol(lastWriteQueueSize)]: 0,
[Symbol(timeout)]: null,
[Symbol(kBytesRead)]: 0,
[Symbol(kBytesWritten)]: 0,
[Symbol(connect-options)]: [Object] },
_header:
'GET /documents HTTP/1.1\r\nAccept: application/json, text/plain, */*\r\nUser-Agent: axios/0.19.0\r\nHost: hastebin.com\r\nConnection: close\r\n\r\n',
_onPendingData: [Function: noopPendingOutput],
agent:
Agent {
_events: [Object],
_eventsCount: 1,
_maxListeners: undefined,
defaultPort: 443,
protocol: 'https:',
options: [Object],
requests: {},
sockets: [Object],
freeSockets: {},
keepAliveMsecs: 1000,
keepAlive: false,
maxSockets: Infinity,
maxFreeSockets: 256,
maxCachedSessions: 100,
_sessionCache: [Object] },
socketPath: undefined,
timeout: undefined,
method: 'GET',
path: '/documents',
_ended: true,
res:
IncomingMessage {
_readableState: [ReadableState],
readable: false,
_events: [Object],
_eventsCount: 3,
_maxListeners: undefined,
socket: [TLSSocket],
connection: [TLSSocket],
httpVersionMajor: 1,
httpVersionMinor: 1,
httpVersion: '1.1',
complete: true,
headers: [Object],
rawHeaders: [Array],
trailers: {},
rawTrailers: [],
aborted: false,
upgrade: false,
url: '',
method: null,
statusCode: 200,
statusMessage: 'OK',
client: [TLSSocket],
_consuming: true,
_dumped: false,
req: [Circular],
responseUrl: 'https://hastebin.com/documents',
redirects: [] },
aborted: undefined,
timeoutCb: null,
upgradeOrConnect: false,
parser: null,
maxHeadersCount: null,
_redirectable:
Writable {
_writableState: [WritableState],
writable: true,
_events: [Object],
_eventsCount: 2,
_maxListeners: undefined,
_options: [Object],
_redirectCount: 1,
_redirects: [],
_requestBodyLength: 18,
_requestBodyBuffers: [],
_onNativeResponse: [Function],
_currentRequest: [Circular],
_currentUrl: 'https://hastebin.com/documents',
_isRedirect: true },
[Symbol(isCorked)]: false,
[Symbol(outHeadersKey)]:
[Object: null prototype] { accept: [Array], 'user-agent': [Array], host: [Array] } },
data:
'<html>\n<head>\n<title>hastebin</title>\n<meta charset="utf-8" />\n<link rel="stylesheet" type="text/css" href="solarized_dark.css" />\n<link
rel="stylesheet" type="text/css" href="application.css" />\n<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>\n<script type="text/javascript" src="highlight.min.js"></script>\n<script type="text/javascript" src="application.min.js"></script>\n<meta name="robots" content="noindex,nofollow" />\n<script type="text/javascript">\n\t\t\tvar app = null;\n\t\t\t// Handle pops\n\t\t\tvar handlePop = function(evt) {\n\t\t\t\tvar path = evt.target.location.pathname;\n\t\t\t\tif (path === \'/\') { app.newDocument(true); }\n\t\t\t\telse { app.loadDocument(path.substring(1, path.length)); }\n\t\t\t};\n\t\t\t// Set up the pop state to handle loads, skipping the first load\n\t\t\t// to make chrome behave like others:\n\t\t\t// http://code.google.com/p/chromium/issues/detail?id=63040\n\t\t\tsetTimeout(function() {\n\t\t\t\twindow.onpopstate = function(evt) {\n\t\t\t\t\ttry { handlePop(evt); } catch(err) { /* not loaded yet */ }\n\t\t\t\t};\n\t\t\t}, 1000);\n\t\t\t// Construct app and load initial path\n\t\t\t$(function() {\n\t\t\t\tapp = new haste(\'hastebin\', { twitter: true });\n\t\t\t\thandlePop({ target: window });\n\t\t\t});\n\t\t</script>\n</head>\n<body>\n<ul id="messages"></ul>\n<div id="key">\n<div id="pointer" style="display:none;"></div>\n<div id="box1">\n<a href="/about.md" class="logo"></a>\n</div>\n<div id="box2">\n<button class="save function button-picture">Save</button>\n<button class="new function button-picture">New</button>\n<button class="duplicate function button-picture">Duplicate & Edit</button>\n<button class="raw function button-picture">Just Text</button>\n<button class="twitter function button-picture">Twitter</button>\n</div>\n<div id="box3" style="display:none;">\n<div class="label"></div>\n<div class="shortcut"></div>\n</div>\n</div>\n<div id="linenos"></div>\n<pre id="box" style="display:none;" class="hljs" tabindex="0"><code></code></pre>\n<textarea spellcheck="false" style="display:none;"></textarea>\n</body>\n</html>\n' }
这是网站本身上的POST请求的示例。
Request URL: https://hastebin.com/documents
Request Method: POST
Status Code: 200
Remote Address: 104.24.121.66:443
Referrer Policy: no-referrer-when-downgrade
cf-cache-status: DYNAMIC
cf-ray: 524f...
content-encoding: br
content-type: application/json
date: Sun, 13 Oct 2019 07:31:02 GMT
expect-ct: max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct"
server: cloudflare
status: 200
via: 1.1 vegur
x-ratelimit-limit: 500
x-ratelimit-remaining: 499
:authority: hastebin.com
:method: POST
:path: /documents
:scheme: https
accept: application/json, text/javascript, */*; q=0.01
accept-encoding: gzip, deflate, br
accept-language: en-US,en;q=0.9
content-length: 4
content-type: application/json; charset=UTF-8
cookie: __cfduid=dd39d5b7c126774b...
origin: https://hastebin.com
referer: https://hastebin.com/
sec-fetch-mode: cors
sec-fetch-site: same-origin
user-agent: Mozilla/5.0...
x-requested-with: XMLHttpRequest
test
答案 0 :(得分:1)
尝试一下。
const axios = require('axios')
axios.post('https://hastebin.com/documents', {
payload: 'test'
})
.then((res) => {
console.log(`statusCode: ${res.status}`)
console.log(`key: ${res.data.key}`)
})
.catch((error) => {
console.error(error)
})