'image not showing it's correct path when rendering in image Component

I am working on a messaging system where user can post message along with image using react.js and node.js. In node part, i used multer library for storing my file and that is working without causing any problem. Here is My code in node end:

app.js:

const postRoutes = require('./routes/post');
const mongoose = require('mongoose');
const multer = require('multer');

const app = express();

app.use(bodyParser.json()); 

app.use('/images',express.static(path.join(__dirname,'images')));

const storage = multer.diskStorage({
    destination: (req, file, cb) =>{
        //ensure that this folder already exists in your project directory
        cb(null, "images");
    },
    filename: (req, file, cb)=>{
        let extension = file.originalname.split('.')[1];
        cb(null, "image-"+Date.now().toString() + '.' +extension)
    }
});

const imageFileFilter = (req, file, cb) =>{
    if(!file.originalname.match(/\.(jpg|jpeg|png|gif)$/)) { 

        req.fileValidationError = "You can upload only image files";
        return cb(null,false, req.fileValidationError);
    }
    cb(null, true)
};

app.use(multer({storage: storage, fileFilter: imageFileFilter}).single('image'));

app.use('/post', postRoutes);
app.use((error,req,res,next)=>{
    console.log(error);
    const statusCode = error.statusCode;
    const message = error.message;
    res.status(statusCode).json({message:message});
});

mongoose.connect(dbUrl)
    .then(()=>{
        app.listen(8080);
        console.log('DB is Connected . Application Start in 8080')
    })
    .catch(err=>console.log(err));

routes/post.js :

const express = require('express');

const postController = require('../controllers/post');

const Post = require('../model/post.model');
const router = express.Router();

// GET /post/messages
router.get('/messages', postController.getPosts);

// GET /post/message/:id
router.get('/message/:id', postController.getPostById);

// POST /post/message
router.post('/message',
    Post.validation,
    postController.createPost);

// Put /post/message/:id
router.put('/message/:id',
    Post.validation,
    postController.updatePost);

module.exports = router;

postController.js :

exports.createPost = (req, res, next) => {
  const errors = validationResult(req);
    console.log(req.file)
  if(!errors.isEmpty()){
    const error = new Error('Validation Failed, entered data is not valid');
    error.statusCode = 422;
    throw error;
  }
  if(!req.file){
      const error = new Error('Invalid Image File');
      error.statusCode = 422;
      throw error;
  }
  const imageUrl = req.file.path;
  const title = req.body.title;
  const content = req.body.content;
  const post = new Post({
    title: title,
    content: content,
    imageUrl: imageUrl,
    createdBy: {
      name: 'lorem_ipsum'
    }
  });

After creating a post output results saved in db:

{
  title: 'Texts',
  imageUrl: 'images\\image-1653121355433.jpg',  
  content: 'Text content',
  creator: { name: 'lorem ipsum' },
  _id: new ObjectId("6288a14b5b9b0ae87b069a08"),
  createdAt: 2022-05-21T08:22:35.438Z,
  updatedAt: 2022-05-21T08:22:35.438Z,
  __v: 0
}

But when i am trying to fetch the data and showing in react application the url is breaking. in my view page image div showing blank and the response I get from api : my image

As you can see my imagePath is : http://localhost:8080/images\image-1653121355433.jpg but react application removing the middle slash and filepath become http://localhost:8080/imagesimage-1653121355433.jpg

here is my view page and image component :

SinglePost.js :

import React, { Component } from 'react';

import Image from '../../../components/Image/Image';
import './SinglePost.css';

class SinglePost extends Component {
  state = {
    title: '',
    author: '',
    date: '',
    image: '',
    content: ''
  };

  componentDidMount() {
    const postId = this.props.match.params.postId;
    fetch('http://localhost:8080/feed/post/' + postId)
      .then(res => {
        if (res.status !== 200) {
          throw new Error('Failed to fetch status');
        }
        return res.json();
      })
      .then(resData => {
        console.log(resData.post)
        this.setState({
          title: resData.post.title,
          author: resData.post.creator.name,
          image: 'http://localhost:8080/' + resData.post.imageUrl,
          date: new Date(resData.post.createdAt).toLocaleDateString('en-US'),
          content: resData.post.content
        });
      })
      .catch(err => {
        console.log(err);
      });
  }

  render() {
    return (
      <section className="single-post">
        <h1>{this.state.title}</h1>
        <h2>
          Created by {this.state.author} on {this.state.date}
        </h2>
        <div className="single-post__image">
          <Image contain imageUrl={this.state.image} />
        </div>
        <h1>{this.state.image}</h1>
        <p>{this.state.content}</p>
      </section>
    );
  }
}

export default SinglePost;

and Image.js :

import React from 'react';

import './Image.css';

const image = props => (
  <div
    className="image"
    style={{
      backgroundImage: `url('${props.imageUrl}')`,
      backgroundSize: props.contain ? 'contain' : 'cover',
      backgroundPosition: props.left ? 'left' : 'center'
    }}
  />
);

export default image;

Can anyone help me to sort this problem out ? What am i missing in my code ?



Solution 1:[1]

Try this

function onEdit(e) {
  const sheet = e.source.getActiveSheet();
  const cell = e.range;
  // AJ = column 36 (master column)
  if(sheet.getName() == "MasterData" && cell.getColumn()==36 && cell.isChecked()){
    sheet.getRange(cell.getRow(),37,1,14).setValue('TRUE')
  }
  // individual columns : 37 (AK) to 50 (AX)
  if(sheet.getName() == "MasterData" && cell.getColumn()>=37 && cell.getColumn()<=50 && !cell.isChecked()){
    sheet.getRange(cell.getRow(),36,1,1).setValue('FALSE')
  }
}

explanation

when a box is checked in column 36 (AJ = 'master column'), all the boxes of the same row between 37 to 50 (AK to AX) will be checked

when an individual box is unchecked between column 37 to 50 (AK to AX) the master box of the same row will be also unchecked

reference

onEdit trigger

Solution 2:[2]

The onEdit(e) simple trigger returns an event object.

The event object contains the information about the spreadsheet that was edited, which you use instead of the "SpreadsheetApp.getActiveSpreadsheet()"

To access the information in the event object, you need to use the 'e':

function onEdit(e) {

  //the sheet that was edited
  var sheet = e.source.getActiveSheet();

  //the cell that was edited
  var cell = sheet.getActiveCell();

  //the row number of the cell that was edited
  var row = cell.getRow();

  //the column number of the cell that was edited
  var column = cell.getColumn();

From there, proceed as you normally would with sheets and ranges.

To update multiple cells at once, you can set the range with getRange(row, column, numRows, numColumns) and then setValues(values). Note that it's setValues(), not setValue().

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2