使用Node.JS的request模块向Ghostbin发POST请求遇406错误求解决
Why am I getting 406 Not Acceptable when posting to Ghostbin with Node.js request module?
Let's break down what's going wrong here and fix it:
The Core Issue
You're targeting the wrong endpoint and using incorrect parameter names. Ghostbin's web form endpoint (/paste/new) is built for browser interactions, not programmatic API calls. The actual API endpoint for creating pastes is https://ghostbin.com/api/v1/pastes, and it expects specific request formatting to work properly.
What Was Wrong With Your Attempts
All three tries failed for these key reasons:
- Incorrect endpoint:
/paste/newreturns HTML for browser users, not structured API responses. When your request doesn't match the expected browser context, the server throws a 406 error because it can't serve a response format your request accepts. - Wrong parameter name: Ghostbin's API uses
content(nottext) to receive the paste content. - Missing/incorrect headers: The API requires JSON-formatted requests and expects an
Accept: application/jsonheader to return a valid API response.
The Working Solution
Here's a corrected version using the request module that will successfully create a paste:
const request = require('request'); request.post({ url: 'https://ghostbin.com/api/v1/pastes', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, json: { content: 'test post', // Optional: Add expiration time (in seconds, e.g., 3600 for 1 hour) // expire: 3600, // Optional: Set syntax highlighting language (e.g., "javascript") // language: 'javascript' } }, function(err, res, body) { if (err) { console.error('Request failed:', err); return; } console.log('Status Code:', res.statusCode); console.log('Paste URL:', `https://ghostbin.com/p/${body.id}`); console.log('API Response:', body); });
Key Notes
- Using the
jsonoption in request automatically sets theContent-Typeheader toapplication/jsonand parses the response as JSON (so you don't have to manually handleJSON.parse(body)). - The API response will include an
idfield you can use to build the public URL of your paste (e.g.,https://ghostbin.com/p/{id}). - If you still run into issues, ensure you're using the latest version of the request module (this code works with most recent versions).
内容的提问来源于stack exchange,提问作者APixel Visuals
相关产品推荐
相关产品推荐

