将带有 axios 的图像发送到 Node.js,然后进一步使用它

Sending an image with axios to Node.js and then using it further

我正在尝试从前端上传一张图片,post 它与 axios 一起上传到后端 (node.js),然后从那里再次 post 它到GroupMe 图片服务。

主要是避免在前端使用 API 令牌,所以我试图先向后端发送请求,然后再发送实际的 API 请求到 GroupMe 图像服务,该服务期望获取图像的 FormData 并发回转换后的图像 URL。

我尝试从前端将 FormData 直接发送到 GroupMe 图像服务,一切正常。但是,为了这样做,我不得不将令牌存储在前端,我认为这不是一个好主意。

下面的工作代码:

let config = {
    headers : {
        'X-Access-Token': myToken,
        'Content-Type' : 'multipart/form-data'
    }
}
let fd = new FormData()
fd.append('name', 'image')
fd.append('file', fileToUpload)

axios.post'(https://image.groupme.com/pictures', fd, config)
.then((response)=>{
    console.log(response)
})
.catch(err =>{
    console.log(err.response)
})

我需要做的是像这样将请求发送到后端:

axios.post(process.env.baseUrl+'/messengerRequests/upload-file/', fd, config)
.then((response)=>{
    console.log(response)
})
.catch(err =>{
    console.log(err.response)
})

现在在后端能够以某种方式获取该 FormData,然后创建另一个 post 对 GroupMe 图像服务的请求,就像我最初在前端所做的那样。

sendMessage: async(req, res) => {
 axios.post('https://image.groupme.com/pictures', ???, config)
 .then((response)=>{
    res.send(response)
 })
 .catch(err =>{
    console.log(err.response)
 })
}

我不知道它出现在axios请求的什么地方。 req.bodyreq.params 中没有任何内容,因此我无法简单地将其进一步传递给下一个 post

有没有办法再次传递这个 FormData? 或者也许有一种方法可以在前端安全地使用令牌?

如果您使用的是 Express,您将需要一些东西来处理 FormData。我以前用 multer 来做类似的事情。我必须将文件保存到本地存储,然后使用 axios 重新发送文件。

因此,使用 Node.js 和 Express / Multer / Request 将图像 post 发送到 GroupMe 应该相对简单。我在后端选择了 Request 而不是 Axios,因为我对 API 更熟悉,但实际上是一样的区别。

Node.js代码(index.js)

const request = require("request");
const express = require("express");
const multer = require("multer");
const upload = multer();

const app = express();
const port = 3000;
const myToken = "" // Your API token goes here.

app.use(express.static("./"));

/* Here we take the image from the client and pass it on to GroupMe */
app.post("/uploadFile", upload.any(), (req, res) => {
    sendImageToGroupMe(req, res);
});

function sendImageToGroupMe(req, res) {

    const options = {
        uri: "https://image.groupme.com/pictures",
        body: req.files[0].buffer,
        method: "POST",
        headers: {
            "X-Access-Token" : myToken 
        }
    }

    request(options, (err, response, body) => {
        console.log("Request complete: Response: ", body);
        if (err) { 
            console.error("Request err: ", err);
            res.status(500).send("Upload failed: ", err.message);
        } else {
            res.status(201).send("Upload successful: GroupMe response: " + body);
        }
    });
}

app.listen(port);

客户端

index.html

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
        <script>

            function uploadFile() {
                var fileToUpload  = document.querySelector('input[type=file]').files[0];       
                let config = {
                    headers : {
                        'Content-Type' : 'multipart/form-data'
                    }
                }

                let fd = new FormData()
                fd.append('name', 'image')
                fd.append('file', fileToUpload)

                axios.post('http://localhost:3000/uploadFile', fd, config)
                .then((response)=>{
                    console.log("Image posted successfully: ", response);
                    showOutput("Image posted successfully: " + response.data);
                })
                .catch(err =>{
                    console.error("Image post failed: ", err)
                    showOutput("Image post failed!");
                })
            }

            function showOutput(html) {
              document.getElementById("output").innerHTML = html;
            }
        </script>
    </head>
    <body style="margin:50px">
        <input type="file" onchange="uploadFile()"><br>
        <p id="output"></p>
    </body>
</html>

所有文件都在同一目录中。您可以去 http://localhost:3000/ 测试 index.html 代码,这将由 Node.js 服务器作为静态文件提供。

我从 GroupMe API 收到如下回复:

{
    "payload": {
        "url": "https://i.groupme.com/157x168.png.940f20356cd048c98478da2b181ee971",
        "picture_url": "https://i.groupme.com/157x168.png.940f20356cd048c98478da2b181ee971"
    }
}

我们将在本地端口 3000 上提供服务,因此要启动服务器:

node index.js