【问题标题】:Mashape Imgur node.js image uploadMashape Imgur node.js 图片上传
【发布时间】:2015-01-12 17:05:47
【问题描述】:

尝试上传用户图片但没有成功。

HTML:

前端 JS:

            var fileInput = document.getElementById('gg_test_input');


            fileInput.addEventListener('change', function(e) {
                var file =  fileInput.files[0];
                var xhr = new XMLHttpRequest();
                var formData = new FormData();


                formData.append("file", file);
                xhr.open('POST', '/gg_upload');
                xhr.send(formData);
            });

我们向其发送请求的 Node.js:

函数(req, res){ var form = new formidable.IncomingForm();

form.parse(req, function(err, fields, files) {
    if( err ) throw err;


    unirest.post('http://httpbin.org/post')
        .header("X-Mashape-Key", "MASHAPE_KEY")
        .header("Authorization", "clientID_KEY")
        .attach('file', files.file.path)
        .end(function (response) {
            console.log(response.status, response.headers, response.body);
        });
});

}

但我明白了:

403 { 'access-control-allow-headers': 'Authorization, Content-Type, Accept, X-Mashape-Authorization',
  'access-control-allow-methods': 'GET, PUT, POST, DELETE, OPTIONS',
  'access-control-allow-origin': '*',
  'cache-control': 'no-store, no-cache, must-revalidate, post-check=0, pre-check=0',
  'content-type': 'application/json',
  date: 'Sat, 15 Nov 2014 10:01:20 GMT',
  etag: '"********************************************"',
  server: 'Mashape/5.0.5',
  'x-ratelimit-requests-limit': '12500',
  'x-ratelimit-requests-remaining': '12468',
  'x-ratelimit-uploads-limit': '1250',
  'x-ratelimit-uploads-remaining': '1248',
  'content-length': '110',
  connection: 'keep-alive' } { data: 
   { error: 'Malformed auth header',
     request: '/3/image',
     method: 'POST' },
  success: false,
  status: 403 }

但是当使用此 curl 测试身份验证时,它可以正常工作:

curl -X POST --include "https://imgur-apiv3.p.mashape.com/3/image" -H "X-Mashape-Key: MASHAPE_KEY" -H "Authorization: Client-ID clientID_KEY" -F "image=@/home/user/Desktop/face.jpg"

请问,unirest.post 是什么?我需要提供更多信息吗?

【问题讨论】:

    标签: node.js api imgur mashape


    【解决方案1】:

    很遗憾,Mashape 上的 Node.js 示例代码是错误的,你应该使用这个:

    var unirest = require('unirest');
    
    unirest.post("https://imgur-apiv3.p.mashape.com/3/image")
    .header("X-Mashape-Key", "MASHAPE_KEY")
    .header("Authorization", "Client-ID CLIENT_ID")
    .header("Content-Type", "multipart/form-data")
    .attach("image", "/Users/example/Projects/imgur/test_image.jpeg")
    .end(function (result) {
      console.log(result.status, result.headers, result.body);
    });
    

    【讨论】:

    • Mashape 上的所有例子都是错误的......他们应该使用你的。
    【解决方案2】:

    您的客户 ID 标头格式不正确(与 cURL 相比),如果您修复它,它将起作用

    【讨论】:

      猜你喜欢
      • 2016-07-17
      • 2014-05-09
      • 2018-02-03
      • 1970-01-01
      • 2016-10-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-06
      相关资源
      最近更新 更多