nodejs / help

:sparkles: Need help with Node.js? File an Issue here. :rocket:
1.46k stars 279 forks source link

How to fix/trouble shoot the missing response from nodejs service? #3718

Closed maifs closed 3 months ago

maifs commented 2 years ago

Version

14.17.5

Platform

windows 10 64 bit

Subsystem

No response

What steps will reproduce the bug?

I am trying to trouble shoot/fix my nodejs upload image api:

My service is being stuck at somewhere. My service is too simple, just uploading the image by resizing through sharp api in a directory and return the full path of that file.

When I select some image at first time then everything works fine and image upload successfully with a response

but When I try to crop that image after clicking on the image and try to save it (at second time) then nodejs service return following response.

I don't why it is being happened, I tried to debug the service code and It didn't stop at anywhere. Flow has been passed/executed successfully, I didn't catch any exception/error in code.

What can be the issue in it because it still displaying

Blockquote failed to load response data. no resource with given identifier found Problem area is in the code of onSaveImage when a server side call is being served/requested. I am using the plugin for image cropping is react-easy-crop. Browser is getting refresh/reload at this line of code

 const jsonRes = await responseMain.json();

I am sharing my nodejs service code as well as reactjs code. please look into it. Thank you.

-----------------package.json of nodejs

{
    "name": "",
    "version": "1.0.0",
    "description": "",
    "main": "index.js",
    "dependencies": {
        "body-parser": "^1.19.0",
        "cors": "^2.8.5",
        "express": "^4.17.1",
        "express-validator": "^6.12.0",
        "handlebars": "^4.7.7",
        "jsonwebtoken": "^8.5.1",
        "mysql": "^2.18.1",
        "nodemailer": "^6.6.1",
        "nodemon": "^2.0.12",
        "sharp": "^0.29.3"
    },
    "devDependencies": {},
    "scripts": {
        "start": "nodemon --inspect index.js",
        "debug": "node --nolazy --inspect-brk=9229 index.js"
    },
    "license": "ISC"
}

------ index.js---------------------------NodeJs

const express = require("express");
const app = express();
const cors = require("cors");
var fs = require("fs");
const fsp = fs.promises;
var path = require("path");
const sharp = require("sharp");

var $pathContentBuilder = path.join(__dirname, "../", "/public/roughdata/uploads/"); 
var $urlpathContentBuilder = "/roughdata/uploads/"; // URL path
app.use(express.json({ limit: "20mb" }));
app.use(cors());
app.use(
    express.urlencoded({
        extended: true,
    })
);
function processImage(image, metadata, filename, isResizeAllow) {
    return new Promise((resolve, reject) => {
        if (isResizeAllow && isResizeAllow === true) {
            // 0.8 MB
            return image
                .resize({
                    width: Math.round(metadata.width / 2),
                    height: Math.round(metadata.height / 2),
                    fit: "cover",
                })
                .toBuffer((err, buf) => {
                    if (err) {
                        console.log("Error occured ", err);
                        return reject(err);
                    } else {
                        return resolve(buf.toString("base64"));
                    }
                });
        } else {
            return image.toBuffer((err, buf) => {
                if (err) {
                    console.log("Error occured ", err);
                    return reject(err);
                } else {
                    return resolve(buf.toString("base64"));
                }
            });
        }
    });
}

app.post("/uploaddetail", async (req, res, next) => {
    const base64Data = req.body.image;
    const filename = req.body.filename;
    let imageResizeResult = "";
    try {
        var inputbuf = Buffer.from(base64Data, "base64"); // Ta-da
        const image = await sharp(inputbuf);
        let metadata = await image.metadata();
        let convertedbase64Data = "";       
        convertedbase64Data = await processImage(image, metadata, filename, false);       
        await fsp.writeFile($pathContentBuilder + filename, convertedbase64Data, "base64");
        let resultResponse = JSON.stringify({
            success: true,
            fullurl: `${$urlpathContentBuilder}${filename}`,
            url: `${filename}`,
            imagename: `${filename}`,
            serverpath: `${$urlpathContentBuilder}`,
        });
        //res.type("json");
        res.status(200).json(resultResponse);
        //res.end();
        //next();
    } catch (e) {
        console.log(e);
        const error = new HttpError(e, 404);
        return next(error);       
    }
});

and following is my reactjs code.

and the client side code is (reactjs) :

const onSaveImage = useCallback(
        async (e) => {
            e.preventDefault();
            if (validate() < 0) {
                return -1;
            }
            try {
                let filename = "";
                let base64Image = "";
                let blobUrl = "";
                debugger;               
                const cropImage = await getCroppedImg(Image, croppedAreaPixels, rotation);                
                setCroppedImage(cropImage);
                setImage(cropImage);
                base64Image = cropImage ? cropImage.replace(/^data:image\/(png|jpeg);base64,/, "") : "";
                const contentType = "image/jpeg";
                if (cropImage) {
                    debugger;                
                    setRow((prevState) => {                        
                        return {
                            ...prevState,                            
                            ["ImageFullUrl"]: cropImage,
                            ["ImageName"]: ImageName ? ImageName : "",
                        };
                    });

                    filename = ImageName ? ImageName : "";                    
                    const settings = {
                        method: "POST",
                        headers: {
                            "Content-Type": "application/json",
                        },
                        body: JSON.stringify({
                            filename: filename,
                            image: base64Image,
                        }),
                    };
                    setLoader(true);
                    let submitUrl = process.env.REACT_APP_SERVER_DOMAIN + `/uploaddetail`;
                    const responseMain = await fetch(submitUrl, settings);
                    const jsonRes = await responseMain.json();
                    if (jsonRes) {
                        let convertedJson = jsonRes;
                        if (convertedJson) {
                            setLoader(false);
                            const uploadedImageUrl = convertedJson.fullurl; // get saved image url
                            const uploadedImageName = convertedJson.imagename;
                            const uploadedServerPath = convertedJson.serverpath;
                            const uploadurl = convertedJson.url;
                            setImageName(convertedJson.imagename);                         
                            setRow((prevState) => {                                
                                return {
                                    ...prevState,
                                    ["ImageName"]: uploadedImageName,
                                    ["ImageServerPath"]: uploadedServerPath,
                                    ["ImageFullUrl"]: uploadedImageUrl,
                                    ["ImageUrl"]: uploadurl,
                                };
                            });
                            if (uploadedImageUrl) {
                                setIsDisabled(false);
                            }
                            setUModalShow(false);                                                        
                            setDetail((prevState) => {                                
                                return {
                                    ...prevState,
                                    ["Content"]: content,
                                };
                            });
                        }
                    }
                }
            } catch (err) {               
                console.log(err);
                showToast("Error!", "Image couldn't be saved");
            } finally {
            }
        },
        [croppedAreaPixels, rotation]
    );

My service is too simple, just uploading the image by resizing through sharp api in a directory and return the full path of that file.

When I select some image at first time then everything works fine and image upload successfully with a response

but When I try to crop that image after clicking on the image and try to save it (at second time) then nodejs service return following response.

I don't why it is being happened, I tried to debug the service code and It didn't stop at anywhere. Flow has been passed/executed successfully, I didn't catch any exception/error in code.

What can be the issue in it because it still displaying

Blockquote failed to load response data. no resource with given identifier found Problem area is in the code of onSaveImage when a server side call is being served/requested. I am using the plugin for image cropping is react-easy-crop. Browser is getting refresh/reload at this line of code

const jsonRes = await responseMain.json(); I am sharing my nodejs service code as well as reactjs code. please look into it. Thank you.

How often does it reproduce? Is there a required condition?

It is coming in the second attempt, first attempt is correct.

Create a node application using my source code as I have mentioned. Your client source should be like below

 const settings = {
                        method: "POST",
                        headers: {
                            "Content-Type": "application/json",
                        },
                        body: JSON.stringify({
                            filename: filename,
                            image: base64Image,
                        }),
                    };
                    setLoader(true);
                    let submitUrl = process.env.REACT_APP_SERVER_DOMAIN + `/uploaddetail`;
                    const responseMain = await fetch(submitUrl, settings);
                    const jsonRes = await responseMain.json();

I am using it in reactjs then it will be reproduced.

What is the expected behavior?

Expected behavior is

It should work and upload the base64 image at second or every attempt.

What do you see instead?

My second attempt is being failed see these images. Browser console is like this.

and display the display the service call status as 200 and success but response it nothing

instead this message is coming "failed to load response data. no resource with given identifier found"

https://i.stack.imgur.com/6CzSQ.png https://i.stack.imgur.com/Y7LQM.png https://i.stack.imgur.com/h1uHx.png

If I try to debug at nodejs server then there is no error there . I debugged the each statement.

Additional information

No response

github-actions[bot] commented 4 months ago

It seems there has been no activity on this issue for a while, and it is being closed in 30 days. If you believe this issue should remain open, please leave a comment. If you need further assistance or have questions, you can also search for similar issues on Stack Overflow. Make sure to look at the README file for the most updated links.

github-actions[bot] commented 3 months ago

It seems there has been no activity on this issue for a while, and it is being closed. If you believe this issue should remain open, please leave a comment. If you need further assistance or have questions, you can also search for similar issues on Stack Overflow. Make sure to look at the README file for the most updated links.