FetchError: request to http://localhost:1337/api/products failed, reason: connect ECONNREFUSED 127.0.0.1:1337

I am trying to build an e-commerce site with Next.JS and Strapi. Whenever I try to request data from Strapi to Next.JS, I always get error:-

FetchError: request to http://localhost:1337/api/products?populate=* failed, reason: connect ECONNREFUSED 127.0.0.1:1337

?populate=* in the link is to receive all data and I also tried without it.

This is how I am requesting data:-

export async function getServerSideProps() {
  let data = await fetch('http://localhost:1337/api/products?populate=*', {
    method: 'GET',
    headers: {
      'Authorization': 'Bearer api-token',
    },
 });
 let products = await data.json();
 return {
   props: { products },
 };
}

I have read many similar questions but can’t find anything. I have checked everything many times but still not working. However, when I make the request with the same API token using thunder client, it gives me a status: 200, and I also receive data in JSON format without any error.
It’s been hours and everything looks good but still not working.

How to properly export/import an object in this nodeJS project?

I have a nodeJS project where I have this file GameState.js with this structure:

const GameState = function(socket){
  this.socket = socket
  //quite a large constructor so I removed most of it
};

//defining all the prototype methods
GameState.prototype.getSocket = function() {
  return this.socket
}

module.exports = GameState;

I’m able use this GameScreen constructor in my gamescreen.js file, by having the two scripts in my gamescreen.html file like this:

<script src = "gamestate.js"></script>
<script src = "gamescreen.js"></script>

So for getting GameState into gamescreen.js I actually don’t need the module.exports, it’s even giving me a (non-breaking) ReferenceError when I use the app, which is quite annoying.

However with my current structure I can’t remove this module.exports as I also have a test file (using jest) where I import GameState with require like this:

const GameState = require("../scripts/gamestate.js");

//the tests here...

So my question is: How do I get GameState in both gamescreen.js and gamestate.test.js, without having the ReferenceError? Right now it’s all working, but it’s not very optimal to get an error in the console when running the app.

How to build something like Figma? [closed]

I am creating a project (non-commercial) with a concept and technology similar to Figma and other UX/UI Design tools.
I found out that Figma uses C++, React and WebGL. But I would like to know in more detail how to create something similar (preferably in Rust).

Can someone help me?

How would I transform an array into a list

So basically, what I want is that if I have an array like this one:

["item", "item1", "item2", "item2", "item2"]

it should be changed into:

 - Itemn- Item1n- Item2 (3x)

I have trying to figure this out for a few hours now and I can’t think of anything, so I thought I should ask here. Help is very much appreciated.

How do I solve error => “Cannot set properties of null (setting ‘innerHTML’)”?

https://codepen.io/bSwastik6/pen/QWQgYPO?editors=1010

There is some problem with the JAVASCRIPT code which I can’t solve. Will be helpful if you guys check the error in the code.

ERROR: {Uncaught TypeError: Cannot set properties of null (setting ‘innerHTML’)}

// Variables

var tenspart = 0;
var minpart = 0;
var secpart = 0;
var time;

// Node Selector

var start = document.querySelector(".start");
var stop = document.querySelector(".stop");
var reset = document.querySelector(".reset");
var tenth = document.querySelector(".tens");
var minute = document.querySelector(".min");
var second = document.querySelector(".second");

// Add Event Listener

start.addEventListener("click", () => {
    clearInterval(time);
    time = setInterval(watchCounter, 10);
});

stop.addEventListener("click", () => {
    clearInterval(time);
});

reset.addEventListener("click", () => {
    clearInterval(time);
    tenspart = 0;
    minpart = 0;
    secpart = 0;
    tenth.innerHTML = "0" + tenspart;
    second.innerHTML = "0" + secpart;
    minute.innerHTML = "0" + minpart;
});

// Event Function

var watchCounter = function () {
    tenspart++;
    tenth.innerHTML = tenspart;
    if (tenspart < 9) {
        tenth.innerHTML = "0" + tenspart;
    }

    if (tenspart > 99) {
        secpart++;
        second.innerHTML = secpart;
        if (secpart < 9) {
            second.innerHTML = "0" + secpart;
        }
        tenspart = 0;
    }

    if (secpart > 59) {
        minpart++;
        minute.innerHTML = minpart;
        if (minpart < 9) {
            minute.innerHTML = "0" + minpart;
        }
        secpart = 0;
    }
};

How to calculate sum of multiple responses inside a loop using javascript?

I have two loops as shown:

        for (var i = 0; i < nearPlacements.length; i++) {
           var meshInstances = nearPlacements[i].model.model.meshInstances;
var mat;
var matEach = 0;
for (var i2 = 0; i2 < meshInstances.length; i2++) {
    mat = parseFloat(meshInstances[i2].mesh.indexBuffer[0].numIndices / 3);
    matEach += mat;
    }
    console.log(matEach);
}

console.log(matEach); outputs data as:

enter image description here

How to display data as a sum of all responses? Thanks

How to access one model to another model in express and mongoose?

I have two model one is productModel.js and another is reviewModel.js. I did child referencing in reviewSchema. product Schema has ratingsAverage and ratingsQuantity property. I want to manipulate these properties of properties inside from reviewModel.js. so that i have used statics method on reviewSchema.

**// reviewModel.js**
const Product = require("./productModel");
const { Schema } = require("mongoose");
const mongoose = require("mongoose");

const reviewSchema = new Schema({
  review: {
    type: String,
  },
  rating: {
    type: Number,
    min: 1,
    max: 5,
  },
  createdAt: {
    type: Date,
    default: Date.now(),
  },
  product: {
    type: mongoose.Schema.ObjectId,
    ref: "Product",
    required: [true, "A review must belong to a tour."],
  },
  user: {
    type: mongoose.Schema.ObjectId,
    ref: "User",
    required: [true, "A review must belong to a user"],
  },
});

// Preventing from duplication of review on same tour from same user
// Combined index
reviewSchema.index({ product: 1, user: 1 }, { unique: true });

// Creating calcAverageRating() static method for calculating average rating and number of ratings on product. It should work on creating, updating and deleting of review.
reviewSchema.statics.calcAverageRating = async function (productId) {
  // "this" represents here model
  const stats = await this.aggregate([
    {
      $match: { product: productId },
    },
    {
      $group: {
        _id: "$product",
        nRating: { $sum: 1 },
        avgRating: { $avg: "$rating" },
      },
    },
  ]);

  console.log(stats, "rrrr");
  // console.log(Product, "product");

  // Problem is coming here i am not able to access productModel
  // const doc = await Product.findByIdAndUpdate(
  //   productId,
  //   {
  //     ratingsAverage: stats[0],
  //     ratingsQuantity: stats[0],
  //   },
  //   {
  //     new: true,
  //     runValidators: true,
  //   }
  // );
};

// As you know static methods only call on Model so we have to think about how to call calcAverageRating() static method. problem is that we have to get this product id which one is used to creating review so we only get this id on document middleware("post") for creating and for updating and deleting we will get from get from query middleware(/^findOne/).

// Document middleware("save")
reviewSchema.post("save", function () {
  this.constructor.calcAverageRating(this.product);
});

reviewSchema.post(/^findOneAnd/, async function () {
  // console.log(await this.findOne());
  this.r = await this.clone().findOne();
  console.log(this.r, "query");
  console.log(Product, "testing");
});

reviewSchema.post(/^findOneAnd/, function () {
  this.r.constructor.calcAverageRating(this.r.product);
});

// reviewSchema.pre(/^find/, function (next) {
//   this.populate({
//     path: "product",
//     select: "name",
//   });
//   next();
// });

// CREATING MODEL
const Review = mongoose.model("Review", reviewSchema);
// We can call here static method but we will not get productId so we have to call this static method before creating of Model.
// Review.calcAverageRating();

// EXPORTING
module.exports = Review;


**// productModel.js**
const mongoose = require("mongoose");
const { Schema } = require("mongoose");
const Review = require("./reviewModel");

// CREATING SCHEMA
const productSchema = new Schema(
  {
    name: {
      type: String,
      required: [true, "Please enter product name"],
      unique: true,
      trim: true,
    },
    slug: String,
    price: {
      type: Number,
      required: [true, "A product must have a price"],
      maxlength: [8, "Price cannot exceeds 8 characters"],
    },
    priceDiscount: {
      type: Number,
      validate: {
        validator: function (val) {
          // this only points to current doc on NEW document creation
          return val < this.price;
        },
        message: "Discount price ({VALUE}) should be below regular price",
      },
    },
    stock: {
      type: Number,
      required: [true, "Please Enter product Stock"],
      maxLength: [4, "Stock cannot exceed 4 characters"],
      default: 1,
    },
    summary: {
      type: String,
      required: [true, "A product must have a summary"],
    },
    description: {
      type: String,
      required: [true, "A product have a description"],
    },
    images: [
      {
        public_id: {
          type: String,
          required: [true, "Images public id is required"],
        },
        url: {
          type: String,
          required: [true, "Images url is required"],
        },
      },
    ],
    ratingsAverage: {
      type: Number,
      default: 0,
    },
    numOfReviews: {
      type: Number,
      default: 0,
    },
    reviews: [
      {
        user: {
          type: mongoose.Schema.ObjectId,
          ref: "User",
          required: true,
        },
        name: {
          type: String,
          required: true,
        },
        rating: {
          type: Number,
          required: true,
        },
        comment: {
          type: String,
          required: true,
        },
      },
    ],
    user: {
      type: mongoose.Schema.ObjectId,
      ref: "User",
      required: true,
    },
    category: {
      type: String,
      required: [true, "A product must belong to a category"],
    },
    createdAt: {
      type: Date,
      default: Date.now(),
    },
    // ratingsAverage: {
    //   type: Number,
    //   default: 4.5,
    //   min: [1, "Rating must be above 1.0"],
    //   max: [5, "Rating must be below 5.0"],
    //   // Declaring custom function for do some opeartion from get value
    //   // set: (val) => Math.round(val * 10) / 10, // 4.666666, 46.6666, 47, 4.7
    //   set: (val) => Math.round(val * 10) / 10,
    // },
    // ratingsQuantity: {
    //   type: Number,
    //   default: 0,
    // },
  },
  {
    toJSON: { virtuals: true },
    toObject: { virtuals: true },
  }
);

productSchema.index({ name: "text", description: "text" });

// VIRTUAL POPULATE
   productSchema.virtual("reviews", {
       ref: "Review",
      foreignField: "product",
       localField: "_id",
     });

// CREATING MODEL
const Product = mongoose.model("Product", productSchema);

// EXPORTING
module.exports = Product;

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/imagesimage-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 ?

Function returning undefined, I know it’s to do with the non-return but I am struggling to solve

I have a function that takes a variable called (compactArray) (there is another function to produce and return a compact array that works fine)

I know it’s because my function is not returning any value, but I am struggling to solve the return = undefined.

the code is below

let a = null;
let b = null;
let operand = null;
let total = null;



function testGrab (compactArray) {
    if(compactArray == typeof(Number) && a == null) {
     return a = compactArray;
    } else if (compactArray == typeof(Number) && a !== null){
        return b = compactArray;
    } else if (compactArray == typeof(String)){
        return operand = compactArray; 
    }
  return total
};


const compactArray = 467; 

console.log(testGrab(compactArray));
console.log(a)

I want this function to take the compactArray returned from a different function and assign it to the correct variable a,b,operand.

is this possible, or would I need to make a function to return the relevant if statement, and then create another function to assign the returned value to the correct variable?

I know it’s because my function is not returning anything but I am stumped at the moment.

knockout.js can you access the binding context from a script?

I have a javascript object graph, an HTML form, and knockout bindings connecting the two. The form is complex, and sometimes the form needs to add some computed observables to some sub-object in our object graph, and I want to do that locally in the the HTML element that has the data-bind which relies on this, I don’t want such knowledge somewhere in some global script.

<div class="widget" data-bind="foreach: subThing">
  <script type="text/javascript">
    $data._scratchpad = ko.computedObservable( ... );
  </script>
  ...
  <input data-bind="value: _scratchpad"/>
  ...
</div>

Now in the context of this script, the binding context is of course not yet set up, so the $data property is not yet available.

But is there some event that I might put on the element or something so I can catch when the bindings are first initialized so I can add the necessary things before the actual data-bind expressions want to refer to them?

How should I map over two arrays without ruining the order of rendered items?

I’m trying to create a chat-bot with some additional features like sending and receiving voice audio. I used two different array states for rendering the text messages and audio messages. In the render section, I map over these arrays separately.

setMessageList((prevlist) => [...prevlist, {id: uuidv4(), message: currentMessage, type: "sender",}, {id: uuidv4(), message: "response.data.data.answer", type:"reciever"}]);


     setAudioList(prevState => [
      ...prevState,
      {id: uuidv4(), audio: audioUrlQuestion, type: "sender", isLoading: isLoadedVoice} , 
      {id: uuidv4(), audio: result.data.filePath , type: "reciever", isLoading: isLoadedVoice}
    ])
 {audioList.map(item => {
            if (item.type === "sender") {
                   //render sender audio tag
            }
            if (item.type === "reciever" && isLoadedVoice === false) {
              // ...
            } else if (item.type === "reciever" && isLoadedVoice === true) {
              //
            }
          })}
          {messageList.map((item) => {
            if (item.type === "sender") {
              //show sender messages
            }
            if (item.type === "reciever" && isLoadedMessage === false) {
               // show received mesgs
            
            } else if (item.type === "reciever" && isLoadedMessage === true) {
              //
            }
          })}

However, everything works in a right order only when user just send audio/text messages without any switching. For example, if your first message is audio and the second one is text, when you want to send the third message which is an audio type again it should show the audio after the text message. But it doesn’t. Instead it will appear after the first audio message(before the text one).
So, how can I render voice messages and text messages in a right order after another?

why can’t I set state using result of resolved promise? [duplicate]

I’d like to rewrite this react component to be a functional component using hooks:
https://github.com/truffle-box/react-box/blob/master/client/src/App.js

Here is my attempt:

import React, { useState, useEffect } from "react";
import SimpleStorageContract from "./contracts/SimpleStorage.json";
import getWeb3 from "./getWeb3";

import "./App.css";

export const App = () => {

    const [storageValue, setStorageValue] = useState(0);
    const [contract, setContract] = useState(null);
    const [web3, setWeb3] = useState(null);
    const [accounts, setAccounts] = useState([]);
    const [networkId, setNetworkId] = useState(null);
    const [deployedNetwork, setDeployedNetwork] = useState();


    useEffect(()=>{
        const setup = async () => {
            try {
                // Get network provider and web3 instance.
                let web3Obj = await getWeb3();
                console.log(web3Obj);  // this is an object
                setWeb3(web3Obj);
                console.log(web3); // this is null

                // Use web3 to get the user's accounts.
                setAccounts(await web3.eth.getAccounts());

                // Get the contract instance.
                setNetworkId(await web3.eth.net.getId());
                setDeployedNetwork(SimpleStorageContract.networks[networkId]);

                let instance = new web3.eth.Contract(
                    SimpleStorageContract.abi,
                    deployedNetwork && deployedNetwork.address,
                );

                // Set web3, accounts, and contract to the state, and then proceed with an
                // example of interacting with the contract's methods.
                setContract(instance);
                await runExample();
            } catch (error) {
                // Catch any errors for any of the above operations.
                alert(
                    `Failed to load web3, accounts, or contract. Check console for details.`,
                );
                console.error(error);
            }
        }
        setup();
    });

    const runExample = async () => {

        // Stores a given value, 5 by default.
        if (contract){
            await contract.methods.set(5).send({ from: accounts[0] });
            const response = await contract.methods.get().call();
            console.log(response);
            setStorageValue(response);
        }
    };


    if (!web3) {
        return <div>Loading Web3, accounts, and contract...</div>;
    }
    return (
        <div className="App">
            <h1>Good to Go!</h1>
            <p>Your Truffle Box is installed and ready.</p>
            <h2>Smart Contract Example</h2>
            <p>
                If your contracts compiled and migrated successfully, below will show
                a stored value of 5 (by default).
            </p>
            <p>
                Try changing the value stored on <strong>line 42</strong> of App.js.
            </p>
            <div>The stored value is: {storageValue}</div>
        </div>
    );
    
}

export default App;

I’m running into a problem: the getWeb3 module returns a promise that I’d like to resolve, then use to set the web3 state. For some reason, the result of console.log(web3Obj) is the expected object, but the result of console.log(web3) is null, even though I use the result of the former to set the latter. Can anyone explain what I’m doing wrong?