问题
This works:
$.post(
'http://api.imgur.com/2/upload.json',
{
key: 'dsfdwerwersf53534dfsfse3',
image: 'http://i.imgur.com/UH17u.png'
},
function( data ) { console.log( data.upload.links.original ); }
);
When I run this in Chrome's console, imgur sends me the url of the uploaded image right away: http://i.imgur.com/KrHMY.png
. Excellent.
.
Now I'm try the same thing on the server-side using node.js but it doesn't work:
var
express = require( 'express' )
, app = express.createServer()
, request = require( 'superagent' );
app.get( '/', function( req, res ) {
request
.post( 'http://api.imgur.com/2/upload.json' )
.send( { key: 'dsfdwerwersf53534dfsfse3', image: 'http://i.imgur.com/UH17u.png' } )
.end( function( data ) {
console.log( data.upload.links.original );
});
});
app.listen( '8080' );
When I run the node.js app, imgur sends back this response:
text: '{"error":{"message":"No API key was sent, and no user is authenticated","request":"\\/2\\/upload.json","method":"post","format":"json","parameters":"image = {\\"key\\":\\"dsfdwerwersf53534dfsfse3\\",\\"image\\":\\"http:\\/\\/i.imgur.com\\/UH17u.png\\"}"}}',
The key part is this: No API key was sent
. Why isn't imgur recognizing the key
I'm sending with the POST
?
I've tried using both request
and superagent
modules. I feel silly not being able to figure out why something so simple isn't working. Appreciate any pointers.
回答1:
jQuery does sometime so much magie that it is hard to see it.
Here I'd bet two thing either, I have not used superagent in month and I had stupid error like this one that made me sad.
But here I bet that the body is a to string at best a json or your object. JQuery by default urlencode just like most API want the POST body to be. Use
var = require('querystring');
/*...*/
.send(qs.encode({ key: '...', image: '...' }))
来源:https://stackoverflow.com/questions/11849894/imgur-uploads-working-via-client-side-javascript-but-not-node-js-flummoxed