Cannot set headers after they are sent to the client but data is being sent

I am new to express.js and I was sending data of a user using mongoose to send data to mongoDB but after I send 1 incorrect data this error pops up and If I try to send a valid user information this error pops up again but the entries are being sent to my mongoDB database.
Case 1:

  • if I send a correct entry : It works
  • if I send another correct entry : It works
  • If I send an incorrect entry : It crashes

Case 2:

  • if I send a correct entry : It works
  • if I send an incorrect entry : It crashes
  • If I send a correct entry : It crashes but it still sends the data to my database

So do I have to reload everytime after it crashes once or there is a better solution to that?

Error:

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at new NodeError (node:internal/errors:387:5)
    at ServerResponse.setHeader (node:_http_outgoing:603:11)
    at ServerResponse.header (D:FilesDesktopProgrammingReactinotebookbackendnode_modulesexpresslibresponse.js:794:10)
    at ServerResponse.send (D:FilesDesktopProgrammingReactinotebookbackendnode_modulesexpresslibresponse.js:174:12)
    at ServerResponse.json (D:FilesDesktopProgrammingReactinotebookbackendnode_modulesexpresslibresponse.js:278:15)
    at Connection.onMessage (D:FilesDesktopProgrammingReactinotebookbackendnode_modulesmongodblibcmapconnection.js:213:9)      
    at MessageStream.<anonymous> (D:FilesDesktopProgrammingReactinotebookbackendnode_modulesmongodblibcmapconnection.js:59:60) 
    at MessageStream.emit (node:events:513:28)
    at processIncomingData (D:FilesDesktopProgrammingReactinotebookbackendnode_modulesmongodblibcmapmessage_stream.js:124:16)  
    at MessageStream._write (D:FilesDesktopProgrammingReactinotebookbackendnode_modulesmongodblibcmapmessage_stream.js:33:9)   
    at writeOrBuffer (node:internal/streams/writable:391:12) {
  index: 0,
  code: 11000,
  keyPattern: { email: 1 },
  keyValue: { email: '[email protected]' },
  [Symbol(errorLabels)]: Set(0) {}
}

Code:
index.js –

const connectToMongo = require('./db');
const express = require('express');
// npm run server

connectToMongo();
const app = express();
const port = 3000;

app.use(express.json());

// * Available Routes
app.use('/api/auth', require('./routes/auth'));
app.use('/api/notes', require('./routes/notes'));


app.listen(port, () => {
  console.log(`Example app listening on port at http://localhost:${port}`)
})

db.js –

const mongoose = require('mongoose');

const mongoURI = 'mongodb://localhost:27017/iNotebook';

const connectToMongo = () =>{
  mongoose.connect(mongoURI).then(()=>{
    console.log('Connected to Mongo Successfully');
  });
}

module.exports = connectToMongo;

routes/auth.js –

const express = require('express');
const router = express.Router();
const User = require('../models/User');
const { body, validationResult } = require('express-validator');



// * Create A User using: POST "/api/auth/". Doesn't require Auth
router.post('/',[
  body('name', 'Enter a valid name').isLength({min: 3}),
  body('email', 'Enter a valid email').isEmail(),
  body('password', 'Password must be atleast 5 characters').isLength({min: 5})
], (req, res)=>{
  const errors = validationResult(req);
  if (!errors.isEmpty()) {
    return res.status(400).json({ errors: errors.array() });
  }
  User.create({
    name: req.body.name,
    email: req.body.email,
    password: req.body.password,
  }).then(user => res.json(user))
  .catch(err => console.log(err),
  res.json({error: 'Please enter a unique value for Email'}))
});
module.exports = router;

routes/notes.js –

const express = require('express');
const router = express.Router();

router.get('/', (req, res)=>{
  
  res.json([]);
});

module.exports = router;

models/Notes.js –

const mongoose = require('mongoose'); 

const NotesSchema = new Schema({
  title:{
    type: String,
    required: true
  },
  description:{
    type: String,
    required: true
  },
  tag:{
    type: String,
    default: "General"
  },
  date:{
    type: Date,
    default: Date.now
  }
});

module.exports = mongoose.model('notes', NotesSchema);

models/User.js –

const mongoose = require('mongoose'); 
const { Schema } = mongoose;


const UserSchema = new Schema({
  name:{
    type: String,
    required: true
  },
  email:{
    type: String,
    required: true,
    unique: true
  },
  password:{
    type: String,
    required: true
  },
  date:{
    type: Date,
    default: Date.now
  }
});

const User = mongoose.model('user', UserSchema);
User.createIndexes();
module.exports = User;

Can’t solve MulterError: Unexpected field in react/express

I tried to send img file and other text information from React to Express server, save img in aws S3 using multer as middleware, and save img url from S3 and other inform in server DB.
I keep getting MulterError: Unexpected field error while I try upload.single or upload.array in multer or change the Content-type etc… I’ve been trying for hours, now I don’t even know how to modify it.
The way to S3 access is to use access/secret access key in .env as an IAM user.

my react side code

const Item = () => {
  
  const {
 
    register,
    handleSubmit,
    formState: { isSubmitting },
  } = useForm({
    defaultValues: {
      itemName: "",
      imgs: null,
      webpImgs: null,
      price: null,
      category: "",
      brand: "",
      sale: null,
    },
  });

  const onSubmit = async (data) => {
  
    const formData = new FormData();
 
    var sumFile = document.querySelector("#sumFile");
    formData.append("sumFile", sumFile?.files[0]);
 
    const blob = new Blob([data], {
      type: "application/json",
    });
    formData.append("info", blob);

    try {
      addItem(formData).then(async (res) => {
        if (res.status === 200) {
          alert("test");
        } else {
          alert("fail");
        }
      });
    } catch (err) {
      return err;
    }
  };

  return (
    <form className="user-form" onSubmit={handleSubmit(onSubmit)}>
      <select {...register("category")}>
        <option value="a">a</option>
        <option value="b">b</option>
        <option value="c">c</option>
      </select>
      <select {...register("type")}>
        <option value="Short">Short</option>
        <option value="Long">Long</option>
        <option value="Dress">Dress</option>
      </select>

      <input {...register("itemName")} placeholder="itemName" />
      <input
        {...register("file")}
        type="file"
        name="sumFile"
        id="sumFile"
        accept="image/*"
      />
      <input {...register("price")} placeholder="price" />
      <input {...register("brand")} placeholder="brand" />
      <input {...register("sale")} placeholder="sale" />

      <button disabled={isSubmitting}>Add</button>
    </form>
  );
};

express code. I wanted to pass img url to next function here but couldn’t try bc I haven’t saved img to S3 yet.

const express = require("express");
const router = express.Router();
const item = require("../controllers/item");
const { S3Client} = require("@aws-sdk/client-s3");
const dotenv = require("dotenv");
const multer = require("multer");
const multerS3 = require("multer-s3");
const s3 = new S3Client();
dotenv.config();

const upload = multer({
  storage: multerS3({
    s3: s3,
    bucket: "bucket name",
    metadata: function (req, file, cb) {
      cb(null, { fieldName: file.fieldname });
    },
    key: function (req, file, cb) {
      cb(null, Date.now().toString());
    },
  }),
});

router.post("/additem", upload.array("sumFile", 2), function (req, res, next) {
  console.log(req.files);
  res.status(200).send("Successfully uploaded ");
});


module.exports = router;

in network req payload

——WebKitFormBoundaryJxBVt4RCvqhg3w9L Content-Disposition: form-data; name=”sumFile”; filename=”a.png” Content-Type: image/png

——WebKitFormBoundaryJxBVt4RCvqhg3w9L Content-Disposition: form-data; name=”info”; filename=”blob” Content-Type: application/json

error detail

Unexpected field MulterError: Unexpected field
at wrappedFileFilter (/Users/home/self/backtest/server/node_modules/multer/index.js:40:19)
at Multipart. (/Users/home/self/backtest/server/node_modules/multer/lib/make-middleware.js:107:7)
at Multipart.emit (node:events:513:28)
at HeaderParser.cb (/Users/home/self/backtest/server/node_modules/busboy/lib/types/multipart.js:358:14)
at HeaderParser.push (/Users/home/self/backtest/server/node_modules/busboy/lib/types/multipart.js:162:20)
at SBMH.ssCb [as _cb] (/Users/home/self/backtest/server/node_modules/busboy/lib/types/multipart.js:394:37)
at feed (/Users/home/self/backtest/server/node_modules/streamsearch/lib/sbmh.js:219:14)
at SBMH.push (/Users/home/self/backtest/server/node_modules/streamsearch/lib/sbmh.js:104:16)
at Multipart._write (/Users/home/self/backtest/server/node_modules/busboy/lib/types/multipart.js:567:19)
at writeOrBuffer (node:internal/streams/writable:392:12)

Unable to perform WebSocket communication using Socket.IO.Client

Want To Do

  • Performe WebSocket using Socket.IO.Client
  • Same thing as following code
  • The code below connects to the WebSocket, receives a message, then sends it and disconnects from the socket.

index.html

<a>Open the console to see stuff, then refresh to initiate exchange.</a>
<script src='script.js'></script>

script.js


const socket = new WebSocket('ws://localhost:3000/ws');

socket.addEventListener('open', function (event) {
    socket.send('Hello Server!');
});

socket.addEventListener('message', function (event) {
    console.log('Message from server ', event.data);
});


setTimeout(() => {
    const obj = { hello: "world" };
    const blob = new Blob([JSON.stringify(obj, null, 2)], {
      type: "application/json",
    });
    console.log("Sending blob over websocket");
    socket.send(blob);
}, 1000);

setTimeout(() => {
    socket.send('About done here...');
    console.log("Sending close over websocket");
    socket.close(3000, "Crash and Burn!");
}, 3000);

Problem I’m having

The following is the code I wrote

  const socket = io('ws://127.0.0.1:3000');
  console.log("socket, ", socket);
  socket.on('connect', () => {
    socket.emit('message', 'Hello Server!');
  });

  socket.on('message', (data) => {
      console.log('Message from server ', data);
  });

  setTimeout(() => {
      const obj = { hello: "world" };
      console.log("Sending blob over websocket");
      socket.emit('message', obj);
  }, 1000);

  setTimeout(() => {
      socket.emit('message', 'About done here...');
      console.log("Sending close over websocket");
      socket.close();
  }, 3000);

I think I cannot connect to server.
Following is a Warning

  connected: false,
  recovered: false,
  receiveBuffer: [],
  sendBuffer: [],
  _queue: [],
  _queueSeq: 0,
  ids: 0,
  acks: {},
  flags: {},
  io: Manager {
    nsps: { '/': [Circular *1] },
    subs: [
      [Function: subDestroy],
      [Function: subDestroy],
      [Function: subDestroy]
    ],
    opts: {
      path: '/socket.io',
      hostname: '127.0.0.1',
      secure: false,
      port: '3000'
    },
    setTimeoutFn: [Function: bound setTimeout],
    clearTimeoutFn: [Function: bound clearTimeout],
    _reconnection: true,
    _reconnectionAttempts: Infinity,
    _reconnectionDelay: 1000,
    _reconnectionDelayMax: 5000,
    _randomizationFactor: 0.5,
    backoff: Backoff {
      ms: 1000,
      max: 5000,
      factor: 2,
      jitter: 0.5,
      attempts: 0
    },
    _timeout: 20000,
    _readyState: 'opening',
    uri: 'ws://127.0.0.1:3000',
    encoder: Encoder { replacer: undefined },
    decoder: Decoder { reviver: undefined },
    _autoConnect: true,
    engine: Socket {
      writeBuffer: [],
      setTimeoutFn: [Function: bound setTimeout],
      clearTimeoutFn: [Function: bound clearTimeout],
      secure: false,
      hostname: '127.0.0.1',
      port: '3000',
      transports: [Array],
      prevBufferLen: 0,
      opts: [Object],
      id: null,
      upgrades: null,
      pingInterval: null,
      pingTimeout: null,
      pingTimeoutTimer: null,
      readyState: 'opening',
      transport: [Polling],
      _callbacks: [Object]
    },
    skipReconnect: false,
    _callbacks: {
      '$open': [Array],
      '$packet': [Array],
      '$error': [Array],
      '$close': [Array]
    }
  },
  nsp: '/',
  _opts: {
    path: '/socket.io',
    hostname: '127.0.0.1',
    secure: false,
    port: '1919'
  },
  subs: [
    [Function: subDestroy],
    [Function: subDestroy],
    [Function: subDestroy],
    [Function: subDestroy]
  ]
}

How to connect to server ?
The path section contains socket.io. Is that part the problem?

How might I change the value of a property in an object created by a function? Is this possible in Javascript?

I want to change a value of a property, in this case, lets say the age of a ‘resident’ (a resident has been created by the function “createResident()” following the move-In command) that occurs at the start of a game. If time were to advance, like with the push of a button “advance year”, how can I change the property “Age” to increment by 1. Is it possible for me to create some sort of copy or track the Resident and its properties and have it dynamically change with any given output from a function. I basically want each Resident and its properties to be displayed in HTML, so the age value would be viewed on the browser. I am completely open to revising this entire thing!

Here is my code:


const testTime = document.createElement("testTime");
testTime.classList.add('testTime');
document.body.appendChild(testTime);
testTime.setAttribute("id", "testTime");
var cEBtn = document.createElement("button");
document.body.appendChild(cEBtn);
cEBtn.innerHTML = "Change Year";
cEBtn.setAttribute("id", "cEBtn");
testTime.innerHTML = "Year: 0";
let year = 0;

function changeYear() {
    year++;
    testTime.innerHTML = "Year:" + " " + year;
    return [year];
};

// Move-In resident

let firstName = ["Carol", "Joe", "Bob", "Matthew", "James", 'Bachelor', 'Rogue', "Bobby"]
let lastName = ["Doe", "Smith", "Thomas", "Johnson", "Broad", "Tyler"]
let gender = ["Male", "Female", "Non-binary"]

randomchoice = object => object[Math.floor(Math.random() * object.length)]

const residents = document.getElementById("Residents");

function createResident() {
    let age = Math.floor(Math.random() * (60 - 18) + 18);
    let first_name = randomchoice(firstName);
    let last_name = randomchoice(lastName);
    var Resident = document.createElement("td");
    Resident.style.backgroundColor = "white";

    Resident.id = "Resident" + " " + residentAmount;
   
    const ResidentObj = {
    First_name: first_name,
    Last_name: last_name,
    ID: residentAmount,
    Status: "Alive" || "Dead",
    Age: age,
    Gender: randomchoice(gender),
    get fullName() {
        return ResidentObj.First_name + " " + ResidentObj.Last_name
    }

    }
    
    residents.append(Resident)
        
        Resident.innerHTML = "Name:" + " " + ResidentObj.fullName + "<br>" + "ID:" + " " + ResidentObj.ID + "<br>" + "Age:" + " " + ResidentObj.Age + "<br>" + "Gender:" + " " + ResidentObj.Gender
        + "<br>" + "Status:" + " " + ResidentObj.Status;
}

function moveInRes() {
    residentAmount += 1;
    createResident()

}


moveInRes()
moveInRes()
moveInRes()
moveInRes()

cEBtn.onclick = function called() { 
    changeYear();
}

I have tried removing the “ResidentObj” from the createResident function. However, that causes HTML to not be able to reference individual names, ages, and other attributes. I want these residents to all have different values of attributes at spawn. I know there has to be a roundabout way of doing this. If not, what other languages do you recommend to do more of this procedural framework?

Thanks!

Converting octal string to number in JavaScript

How do I convert octal strings (“001”, “06”, “04”, etc.) to actual numbers while keeping the zeroes (001, 06, 04, etc.) in Node.js?

I have an array as a string, but I can’t parse that array because it has octals in it, so doing JSON.parse doesn’t do the trick.

I need actual numbers, not strings.

I can convert the string to an actual array of strings (the numbers are now the strings). This is what I have so far:

const theArray = '[03, 001, 02, 3, 44]';

// causes an error because of octals: JSON.parse(theArray);

// remove the brackets and white spaces
const octals = theArray.replace(/^[|]$/g, '').replace(/ /g, '').split(',');

// convert strings to numbers
const final = octals.map(x => {
  if(x.length > 1 && x[0] === '0') return parseInt(x, 8);
  else return parseInt(x, 10);
});

// final result
console.log('final: ', final);

Length validation of masked Input field

I have the following masked field:

<input id="phone1" placeholder="(___) ___-____"/>

masking is done like this:

 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.inputmask/3.3.4/jquery.inputmask.bundle.min.js"></script>
        <script>
        $("#phone1").inputmask({ "mask": "(999) 999-9999" });
        </script>

I want to do the length validation of the phone field. The phone field should be exactly 10 characters long or with masked input, it should be 14 characters long.
I don’t want to do the validation on submit button, but I want to do the length validation of phone field “onfocusout” or when someone tabs out of the field. I just want to display a message underneath the phone field saying “this field should be 10 characters long” if someone puts less than 10 character. This masking is not letting the user put more than 10 character. This phone field is not a required field.

any help will be highly appreciated.

after ajax call javascript oncall function no work

1.After ajax call,how to make javascript oncall work?
index.php

#this code no work 
        function sortTable(columnName){
        var sort = $("#sort").val();
        $.ajax({
            url:'fetch_details.php',
            type:'post',
            data:{columnName:columnName,sort:sort},
            success: function(response){
           
                $("#empTable tr:not(:first)").remove();
                
                $("#content").append(response);
                if(sort == "asc"){
                    $("#sort").val("desc");
                }else{
                    $("#sort").val("asc");
                } }});}

#this code work well

function getresult(url) {
    $.ajax({
        url: url,
        type: "GET",
        data: { rowcount: $("#rowcount").val() },
        success: function(data) {
            $("#pagination").html(data);
             
        },
        error: function() { }
    });
}

2.here work well if oncall itself only but when combine others can’t work

function scrollToTop() {
        window.scrollTo(0, 0);
      }



#here is print side
<div id="pagination">
<input type="hidden" name="rowcount" id="rowcount" />
</div>

<script>
getresult("getresult.php");
</script>

getresult.php

$output .='<th><span sortTable("cus_code");scrollToTop();>Code</span></th>';
print $output;

After ajax successful call,the onclick javascript no working
but when onlick scrollToTop only no problem

Onclick callback with fetch method in Html language

I have the following html code:

<!doctype html>
<html>

<head>
    <title>Online Strategy</title>
</head>

<body>
    <iframe name="dummyframe" id="dummyframe" style="display: none;"></iframe>
    <form action='/result' method=POST target="dummyframe">
        <textarea id="editor" name="name"></textarea>
        <button type=submit>Run</button>
    </form>
    <textarea id="editor2" name="nam2"></textarea>
    <script>
        function GetData() {
            console.log("my ssss");
            fetch("/result")
                .then((response) => {
                    var upperCase = response.json();
                    console.log("dddd");
                    var upperCase = upperCase.toUpperCase();
                    document.getElementById("outputText").innerHTML = upperCase;
                })
        }
    </script>
</body>

</html>

What I am trying to do is as following:

  1. I input some text in the first textarea, then I click the Run button, then in url 127.0.0.1/result, will have a respone
  2. I fetch the respone, and paste the body into the second textarea.

But it doesn’t work as expected, it has error 404 not found.

What am I doing wrong?

The server side is like this:

#![allow(unused_imports)]

use std::time;

use actix_web::{
    middleware, web, App, HttpRequest, HttpResponse, HttpServer, Responder, Result,
    get,
    post,
    http::{
        header::{self ,ContentType},
        Method, StatusCode,
    }
};
use actix_files::Files;
use serde::{Serialize, Deserialize};

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    HttpServer::new(|| {
        App::new()
            .service(get_html)
            .service(show_result)
    })
    .bind(("127.0.0.1", 8081))?
    .run()
    .await
}

#[get("/")]
async fn get_html() -> impl Responder {
    HttpResponse::Ok()
        .content_type("text/html")
        .body(include_str!("../form2.html"))
}

#[post("/result")]
async fn show_result(params: web::Form<InputCodes>) -> impl Responder {
    let mut res = format!("your input is {}, and I have got it in {:?}", params.name, time::Instant::now());
    HttpResponse::Ok()
        .content_type("text/plain")
        .body(res)
}

#[derive(Serialize, Deserialize)]
pub struct InputCodes {
    pub name: String
}

which is some rust codes. The function show_result handle the form post, and write some word into the /result webpage.

Avoid being affected by website’s default CSS or JS

I use Tampermonkey to write a JS script in a website.

It should be on the right of the website’s page like this.Correct style

And it’s correct in one path of the website. But when I use the same script on another path of the website. It has a wrong style like this.Wrong style

The elements added by my script isCode

I’ve tried to put it in Shadow DOM. But it doesn’t work.

My tampermonkey script just contain createElement and some style, so I may not show it.

Can anyone help me with this problem please?

Expecting the problem could be solved.

Checking if jasmine test is called with a done callback

I’d like to replace some functions inside of test environment to make sure that they’re only called inside test with done callback available. This is to catch (for example) cases where setTimeout is used in a test which does not wait for completion. I’m trying to achieve something like UnhandledPromiseRejection here, but for timers.

But the part I can’t figure out is: How would I check if the test I’m currently running is using the done callback or not? (in a function down the stack, not in the test itself)

How to get an image from user on webpage and store this image in sql server database using asp.net?

I am making a website with profiles of users and there they can upload their avatar. And I need to get a photo from user and store this in users database. First got an image from user and send information to server:

    saveButton.onclick = (() => {
        const file = photoInput.files[0];
        const reader = new FileReader();
        reader.readAsArrayBuffer(file);
        reader.onload = (async () => {
            const bytes = reader.result;
            const description = descriptionInput.value;
            const data = JSON.stringify({
                photo: bytes,
                description
            });

            await fetch("[username]/changedata", {
                method: "PUT",
                headers: {
                    "Content-Type": "application/json"
                },

                body: data
            });

            window.location.reload();
        });
    });

Then tried to store this image in users database:

        app.MapPut("{username}/changedata", async (string username, HttpContext context) =>
        {
            var data = await context.Request.ReadFromJsonAsync<UserDataChange>();
            using var con = new SqlConnection(connection);
            await con.OpenAsync();
            var command = new SqlCommand();
            command.Connection = con;
            command.CommandText = "UPDATE [users] " +
                                  "SET description=@description, picture=@picture " +
                                  "WHERE username=@username";
            command.Parameters.AddWithValue("username", username);
            command.Parameters.AddWithValue("description", data.Description);
            command.Parameters.AddWithValue("picture", data.Photo);
            await command.ExecuteNonQueryAsync();
            await con.CloseAsync();
        });

UserDataChange class:

public class UserDataChange
{
    public byte[] Photo { get; set; }
    public string Description { get; set; }
}

But byte[] is invalid type for this situation.