如何从 Node.js 服务器向客户端发送结合随机数的图像

问题描述

所以,我是 Web 开发的新手,我只是想了解基础知识。任何关于我在哪里可以找到解决此问题的提示的想法都会有很大帮助。

当我的客户输入 url http://localhost:5000/creatAccountPage 服务器向他发送一个基本的 html 页面。然后html页面直接调用javascript方法getCaptachaimage():

async function getCapatchaimage()
{
        const transmittingData =
        {
          clientIdi: "152412",};
        const options = 
         {
            method:'POST',headers: {'Content-Type':'application/json'},body:JSON.stringify(transmittingData)
         };
        
        const response = await fetch('/getCaptchaimage',options);
        const jsonResponse = await response.json();
        document.getElementById("memory").innerHTML = jsonresponse.randomKey+"";
        document.getElementById("captcha_pic").src = jsonresponse.image; //image is not the right type for this to work. I think i need  to transform my json data to the right format.
}

getCapatchaimage() 方法假设从服务器获取图像和变量 randomKey。 下面是我用于发布请求的服务器代码 /getCaptachaimage 我正在使用 Node.js、express 和 Node-Fetch。

//these are not all the requires but I'm just putting the essentials for this issue.
const fetch = require('node-fetch');
const express = require('express');
const app = express(); 

app.post("/getCaptchaimage",function(req,res)
{
var randomNumber = Math.random()* 100000;
var fullKey = randomNumber +process.env.CAPTCHA_SECRET+"";
const verifyUrl = `http://image.captchas.net?client=demo&random=`+fullKey; //I'm getting my image from an external server I can't get it directly from the client code else the client would kNow the fullkey which he is not suppose to kNow.
fetch(verifyUrl)
.then((body) => {
  return res.json({image: body.body,randomKey: randomNumber}); //I suppose I should probably be transforming my image in to a specific format here too. 
});
});

我的一般想法是将我的图像与我的随机密钥一起传输,只是将图像数据与变量 randomkey 一起放入 json 对象的字符串变量 image > 然后找到一个方法将字符串图像数据转换为我需要的格式:document.getElementById("captcha_pic").src = ????

知道如何转换我的图像数据以使其正常工作吗?

由于 javascript 中没有明确的变量类型,我什至无法理解服务器代码的 fetch 函数中数据的格式是“body”。 Node-fetch api 中的所有解释要么我不明白,要么没有告诉我我需要知道什么。 https://www.npmjs.com/package//node-fetch#buffer

在此先感谢您的帮助。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)