Socket I.O configuration with NodeJs and Nginx is not working based on the documentation

I’m deploying my app version with newly configured websocket . I’m using socket.io library, nodejs in the server backend, react in frontend and nginx as a reverse proxy. However, unfortunately it’s not working when I deploy it to production. There is no error being log and most of the configuration I searched are not working.

NGINX CONFIGURATION:

    # API Server
    map $http_origin $port {
    default 0;
    ~(https://(www.domain).com) 8080;
    ~(https://(preprod.domain).com) 8081;
    ~(https://(dashboard.domain).com) 8082;
    }

   map $arg_destination $destination {
    default 0;
    server 1; # dashboard.domain.com @ port 8082
    remote 2; # www.domain.com @ port 8080
   }

   server {
    include /etc/nginx/includes/my_folder/port.conf;
    server_name api.domain.com;
    include /etc/nginx/includes/my_folder/ssl.conf;

    if ($blocked_user_ip = 1) {
            return 403;
    }

    if ($port = 0) {
            return 403;
    }

    location / {
            include /etc/nginx/includes/my_folder/added_headers.conf;
            include /etc/nginx/includes/my_folder/proxy_headers.conf;
            if ($destination = 2) {
                    proxy_pass http://127.0.0.1:8080;
            }
            if ($destination = 1) {
                    proxy_pass http://127.0.0.1:8082;
            }
            if ($destination = 0) {
                    // PORT 8081 will pass here
                    proxy_pass http://127.0.0.1:$port;
            }
    }

    error_page 403 @error;
    location @error {
            root /var/www/my_directory/errors;
            try_files /403.html /403.html;
    }
}

NODEJS CONFIGURATION:

const express = require('express')
const app = express()
const { createServer } = require('http')
const httpServer = createServer(app)
const io = require('socket.io')(httpServer, { 
   cors: { 
     origin: [process.env.CLIENT_URL, process.env.DASHBOARD_CLIENT_URL] 
     } 
})

io.on('connection', (socket) => {
  socket.on('test', (data) => {
     // THIS MESSAGE IS NOT LOG. BECAUSE THE SERVER IS NOT RECEIVING IT FROM THE CLIENT.
     console.log(data?.message) // Hi, Server!
  })
  // Other codes...
})

const server = httpServer.listen(8081)
module.exports = server

REACT CONFIGURATION:

import { io } from 'socket.io-client'

const socket = io('https://api.domain.com', {})

socket.emit('test', { message: 'Hi Server!'})

// Other codes...

VERSIONS:

NGINX: 1.18.0 (Ubuntu)

NODEJS: v18.12.1

REACT: 18.2.0

EXPRESS: 4.18.2

SUMMARY: The general issue is the backend and frontend are not connected. It happens only in production but in local, its working properly.

URL with hash behaves differently when used with window.open() method without window.location.href property

I am not familiar with Javascript, and would be grateful if you could enlighten me regarding the following observation.

I have this Javascript function which should navigate to a page with param string appended. For example:

savebuttonClick() {

       window.open(encodeURI("/lightning/n/Test_Win_Open_Child#Id=123"),"_self");    
     

    }

However, the above script would navigate to the correct URL, but with a blank page displayed.

Changing the scripts by adding the constructing the URL with the window.location.href property first before navigating with the window.open() method would addressed the issue. The page will be displayed as expected, and the parameter (Id)’s value (123) will be passed to the page:

       window.location.href = encodeURIComponent("/lightning/n/Test_Win_Open_Child#Id=123");
       window.open(window.location.href,"_self");      

Or, replacing the hash(#) with question mark (?) would also work:

       window.open(encodeURI("/lightning/n/Test_Win_Open_Child?Id=123"),"_self");    

Can someone please help explain the above observation?

Thank you very much!

Using cached results when calling refetch in react-query

I have a component that uses useQuery to fetch and display a list of Cities.

Cities.js

 const { data, isInitialLoading, isError, refetch } = useQuery(
    ["cities"],
    () => axios.get("http://localhost/cities"),
    {
      staleTime: 10000, 
    }
  );

  // Display loading indicator
  if (isInitialLoading) {
   return <div>Loading...</div>;
  }

  return (
      // Display cities
      {data.map(city => {
         return <p> City: {city.name} </p>
      })}

     // Call refetch method once clicked
     <button onClick={() => refetch()}> call refetch</button>
  ) 

The button displayed above should refetch data once clicked. My question is that when the refetch method is called manually like in the example above, does react-query search cache first, and then return a cached result if it exists, or does refetch always make a brand new fetch request to the specified endpoint? I have set staleTime to 10 seconds in my example, therefore would refetch return the cached result for 10 seconds, and then make new calls to the endpoint afterwards once data is considered stale? If not, what alternative solutions could I implement in order to make use of cached results when making manual refetch calls? Thanks.

I use the swiper from react.js, but the operation of the image is different from the local server and the actual server

Locally, when you press the next button or the previous button, you go one by one, but on the actual production site, you go two by one. Local init is [f, f, f], but it appears as [f, f, f, f] on the production server. (A total of 6 images)

If you reload it from a page that contains that component, it will run as normal. If you refresh it, it’s working normally

Below is the corresponding code.

<div class="crs_meal slider_type2">
      <div class="img_slider prod2_2 swiper-container">
        <div class="swiper-wrapper">
          <Swiper
            modules={[FreeMode, Navigation, Thumbs]}
            thumbs={{ swiper: thumbsSwiper && !thumbsSwiper.destroyed ? thumbsSwiper : null }}
            spaceBetween={0}
            navigation={true}
          > 
            {props.images.map(image => {
                return (
                  <SwiperSlide>
                  <img src={image.src} key={image.src} className="fit_img"/>
                  </SwiperSlide>
                )
            })} 
          </Swiper>
        </div>
      </div>

      <div class="thumb_slider crs1_1 swiper-container">
        <Swiper
          onSwiper={setThumbsSwiper}
          modules={[FreeMode, Navigation, Thumbs]}
          spaceBetween={10}
          slidesPerGroup={1}
          slidesPerView={4}
          freeMode={true}
          watchSlidesProgres={true}
        >  
          {props.images.map(image => {
              return (
              <SwiperSlide className="swiper-slide">
              <img src={image.src} key={image.src} className="fit_img"/>
              </SwiperSlide>
              )
          })}
        </Swiper>
      </div>
    </div>

2 seconds after the swiper component was set, I only set the same image to the new variable as I thought it would need to be refreshed. However, since the data is set after 2 seconds, an error occurs because the swiperImages does not have a value before 2 seconds. How should I resolve this?

Below is the corresponding code.

export default function CustomSwiper(props) {
  const [thumbsSwiper, setThumbsSwiper] = useState(null);
  const [swiperImages, setSwiperImages] = useState();

  useEffect(() => {
    /* Set a timer that runs once after 2 seconds */
    const timeoutId = setTimeout(() => {
      console.log("Run in 2 seconds");
      setData();
    }, 2000);
    
    /* Clean up timeout when components are unmounted */
    return () => clearTimeout(timeoutId);
  }, []); /* Hand over empty arrays and run only when components are mounted */

  function setData() {
    /* Perform the tasks required for renewal */
    const newData = [...props.images];
    setSwiperImages(newData);
  }

  return (
    <>
    <div class="crs_meal slider_type2">
      <div class="img_slider prod2_2 swiper-container">
        <div class="swiper-wrapper">
          <Swiper
            /* onInit={(swiper) => this.setData()} */
            modules={[FreeMode, Navigation, Thumbs]}
            thumbs={{ swiper: thumbsSwiper && !thumbsSwiper.destroyed ? thumbsSwiper : null }}
            spaceBetween={0}
            navigation={true}
            slidesPerGroup={1}
          > 
            {(swiperImages && swiperImages.length > 0 ? swiperImages : props.image).map(image => {
                return (
                  <SwiperSlide>
                    <img src={image.src} key={image.src} className="fit_img"/>
                  </SwiperSlide>
                )
            })} 
          </Swiper>
        </div>
      </div>

      <div class="thumb_slider crs1_1 swiper-container">
        <Swiper
          onSwiper={setThumbsSwiper}
          modules={[FreeMode, Navigation, Thumbs]}
          spaceBetween={10}
          slidesPerGroup={1}
          slidesPerView={4}
          freeMode={true}
          watchSlidesProgres={true}
        >  
          {(swiperImages && swiperImages.length > 0 ? swiperImages : props.image).map(image => {
              return (
              <SwiperSlide className="swiper-slide">
                <img src={image.src} key={image.src} className="fit_img"/>
              </SwiperSlide>
              )
          })}
        </Swiper>
      </div>
    </div>
    </>
  );
}

Token Cookie Not Setting on iOS (Safari) – Vite + React Client, Express.js Server

I have developed an application using Vite + React for the client side and Express.js for the server side. The login functionality works seamlessly on computers and Android devices. However, I encountered an issue when attempting to log in from Safari on iOS. After thorough testing, it appears that the token cookie is not being set when verifying the login status (only in iOS).

After verifying username and password I do this

const token = createAccessToken(user);
  res.cookie("token", token, {
    maxAge: 315360000,
    sameSite: "None",
    secure: true,
  });
  return res.status(200).json(user);

Then to validate the token on the server I do this

validateToken(token)
  .then((user) => {
    return res.status(200).json(user);
  })
  .catch(() => {
    return res.status(401).json({ message: "Token invalido o expirado" });
  });

Finally, my CORS options

const corsOptions = {
  origin: [
    "http://localhost:5173",
    "https://some_url.vercel.app",
    "http://192.mi_ip:19006",
  ],
  methods: "GET,HEAD,PUT,PATCH,POST,DELETE",
  credentials: true,
  optionsSuccessStatus: 204,
};

Server consistently returns a 401 error, and after extensive testing, it’s evident that the token is not present. It’s important to note that the application works flawlessly on other platforms.

The client is hosted on Vercel, and the server is on Fly.io. I’m specifically encountering this issue on iOS (Safari).

Any insights or suggestions on why the token cookie might not be setting on iOS would be greatly appreciated. Thank you!

Submit data is only received in the first tab

I have the following code used to divide 2 tabs, one tab to submit data using Ckeditor, one tab to save data using Codemirror.

    <div class="form-group">
        <label class="form-label" asp-for="Content"></label> <span asp-validation-for="Content"></span>
        <div class="controls">
            <div class="nav-tabs-outer">
                <ul class="nav nav-tabs js-tabs">
                    <li class="active text-center"><a href="#tab1" data-toggle="tab">TAB1</a></li>
                    <li class="text-center"><a href="#tab2" data-toggle="tab">TAB2</a></li>
                </ul>
                <div class="tab-content">
                    <div id="tab1" role="tabpanel" class="tab-pane active fade in">
                        <textarea id="ricktextContent" seo-page-content class="form-control form-control-t" rows="3" placeholder="Mô tả" asp-for="Content"></textarea>
                    </div>
                    <div id="tab2" role="tabpanel" class="tab-pane fade in">
                        <textarea id="ricktextContentDiv"  class="form-control form-control-t" rows="3" placeholder="Mô tả" asp-for="Content"></textarea>
                    </div>
                </div>
            </div>
        </div>
    </div>

and I have the following js snippet to add and edit data

var _page = 1;
$(function () {
    $("[search-advance]").toSearch();
    $("[button-popup]").toPopup();
    $("[button-open-file-manager]").toButtonOpenFile();
    $("[button-submit]").toSubmit(null, null, function () {
        onRefeshValue();
    });
    $("[button-delete]").toDelete();
    $("[button-post]").toPost(null, null, function () {
        onRefeshValue();
    });
    getDataGrid(1, true);
});
var cm1;


function initRickText() {
    cm1 = CodeMirror.fromTextArea(document.getElementById("ricktextContentDiv"), {
        lineNumbers: true,
        mode: "text/html",
        matchBrackets: true,
        lineWrapping: true,
        autoRefresh: true
    });

    $("ricktextContent").toRickText({ customConfig: 'configRickText.js', filebrowserImageBrowseUrl: "@Url.Action("Manager", "FileManager", new { area = "Base", path = "Blog/" })" });
    $("[button-update-status]").toPost(function (rs, $this) {
        swal({
            title: "Thông báo!",
            text: rs.message,
            type: rs.type,
            confirmButtonText: "Đóng!"
        });
        setTimeout(function () {
            $this.button('reset');
            setTimeout(function () {
                statusButtonEdit(false);
            }, 200);
        }, 300);
        coSoYTeId
    }, function () {
        return serializedData;
    });
}

function onRefeshValue() {
    document.getElementById("ricktextContentDiv").value = cm1.getValue();
}
function getDataGrid(page, first = false) {
    _page = page;
    $("[grid-index]").toGridView(first, page, function () {
        if (decodeURIComponent(location.hash.substr(1)) == "openPopup") {
            try {
                // $("[data-open-edit]")[0].click();
                const fullUrl = window.location.href;
                const url = new URL(fullUrl);
                const code = url.searchParams.get("code");
                const language = url.searchParams.get("language");
                if (!code || !language) {
                    return
                }
                const hidePopup = $("#edit-by-code-and-language").attr("href", `/Admin/Manager/StaticInformationManager/EditByCodeAndLanguage?language=${language}&code=${code}`);
                hidePopup.click();
            } catch (e) {
                console.log(e);
            }
        }
    });
}
function reGetDataGrid(e) {
    if (e != null) {
        _page = 1;
        $("[name='language']").val($(e).attr("data-val"));
    }
    getDataGrid(_page, false);
}
function onRefesh() {
    cm1.refresh();
};

Now i am facing the error that when i add data i can only add with , means adding with Ckeditor, but adding with Codemirror will be null, I think it’s because of the ordering because when I set first, meaning Codemirror will be in the first tab so it will only add gets data using Codemirror and Ckeditor will be null.
I tried a few ways but they didn’t work very well. I hope everyone can suggest some solutions for me. Sincerely thank

I just want to be able to submit data using both ckeditor and codemirror, not just one of the two

how to pass the context.application.createDocument() to the blob to download in javascript

I am trying to download the context.application.createDocument()

var myDoc = context.application.CreateDocument("base64 format string that shows in document");
//myDoc.open();
var body = myDoc.body;
downloadDoc(body);

function downloadDoc(docBody: any){
  var blob = new Blod([docBody], type: 'application/vnd.ms-word'});
var url = window.URL.createObjectURL(blob);
var a= document.createElement('a');
a.href =url;
a.download = 'myDocFile.doc';
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
}

the result of the code is showing [Object] [Object] in doc file, it is not showing the text having some styles

Is there a relationship between react re-rendering and DOM up-to-date

I checked that the input returned by a particular react component was drawn on the screen and found that input from the f12 console to the document.querySelector.
However, only null was returned, and it was not until the component returning that input was re-rendered that input was properly returned.

So even if an element is drawn on the screen, if the react component returning that element is not re-rendered, the dom is not updated?

I thought that the input is drawn on the screen, and I can check the input on the f12 console, so of course I can bring it to the document.querySelector.

To summarize, it’s like this

at F12 console,
document.querySelector(‘input[data-id=”test”]’) => null
after react componenet re-rendered
(There is no change in the screen due to the re-render of the react component)
document.querySelector(‘input[data-id=”test”]’) => input

how is it possible?

ps.
Of course, I know it’s a bad way to approach dom directly from React, but I couldn’t help it for personal business reasons.

document.querySelector(‘input[data-id=”test”]’) => input

JS: inline date substring…how to prevent space before?

Given:

<p id="copyright">
&copy;&nbsp;&apos;
<script>
document.getElementById('copyright').appendChild(document.createTextNode(new Date().getFullYear().toString().substr(-2)))
</script>
Company Name
</p>

How does one prevent the space between the ‘ and the two digit year, i.e.,
© ‘ 24 Company Name?

Mongodb get list of IDs for only the array objects that were updated

Here is an example of my collection “messages”.

{[
  _id: xxx,
  shipment: {
   _id: xxx
  },
  messages: [
    { 
      _id: 123,
      origin: 'driver'
      isRead: false,
      ...
    },
    { 
      _id: 234,
      origin: 'driver'
      isRead: false,
      ...
    },
    { 
      _id: 345,
      origin: 'driver'
      isRead: true,
      ...
    },
    { 
      _id: 456,
      origin: 'dispatch'
      isRead: false,
      ...
    },
  ]
]}

I’m updating the array objects using the following code which works great, however this returns the entire document back with all array objects, and I need to return a list of only the objects that were updated so I can pull a list of their IDs.

const message = await MessageModel.findOneAndUpdate(
{
  _id: messageId
},
{
  $set: {
    'messages.$[elem].isRead': true
  }
},
{
  arrayFilters: [{
    'elem.isRead': false,
    'elem.origin': 'driver'
  }],
  new: true
}
);

Output I need in some form so I can grab the IDs that were updated to process further:

messages: [
    { 
      _id: 123,
      origin: 'driver'
      isRead: true,
      ...
    },
    { 
      _id: 234,
      origin: 'driver'
      isRead: true,
      ...
    }
]

const ids = [123,234];

I understand it’s returning the entire document, but I can’t figure out the best route to grab only what’s updated without doing multiple queries and comparing.

I tried working with aggregate but am new to that and can’t figure it out.

Any help greatly appreciated on the best route.

live-server // Visual Studio Code // UnauthorizedAccess

live-server : No se puede cargar el archivo C:UsersarevalAppDataRoamingnpmlive-server.ps1 porque la ejecución de 
scripts está deshabilitada en este sistema. Para obtener más información, consulta el tema about_Execution_Policies en 
https:/go.microsoft.com/fwlink/?LinkID=135170.
En línea: 1 Carácter: 1
+ live-server
+ ~~~~~~~~~~~
    + CategoryInfo          : SecurityError: (:) [], PSSecurityException
    + FullyQualifiedErrorId : UnauthorizedAccess

I’m trying to run live-server in my Visual Studio Code terminal, and it’s throwing this error. How do I fix this error?

How to get relatedVideos based on videoId from youtube API v3?

I am working on a YouTube clone from YouTube API v3, whereas I need to related videos list based on the current playing video’s videoId.

async function getApiData(videoId) {
    const res = await apiRequest('/search', {
        params: {
            part: 'snippet',
            videoCategoryId: videoId, // relatedToVideoId : videoId
            maximumResult: 10,
            type: 'video'   
        }
    })
    console.log("res", res)
    return res;
}

In the params, I have passed videoCategoryId/relatedToVideoId, in different requests.
but it sends an error message.

What would be the correct way to get a related video list from the YouTube API based on the videoId?

Thanks for your support

this context in JavaScript

In the following code, the “this” keyword references the “myName” object. Why doesn’t the “this” in console.log reference the “window” object, since it is really “window.console.log”?

class Name {
  constructor(firstName) {
    this.firstName = firstName;
  }
  superGreet() {
    console.log('I am', this.firstName);
  }
}
 
let myName = new Name("Jay");
myName.superGreet();

How exactly does the chatgpt user interface retrieve data?

Using the browser’s developer tools we can “hijack” the fetch/xhr requests or observe any established websocket connection made from the a given platform to the server.

Listening to the outgoing traffic on twitter for example is pretty easy since its nothing but bunch of rest api calls. But chatgpt seems to be more complicated.

It does indeed send a request (“https://chat.openai.com/backend-api/conversation”) which contains the user question — but the response does not contain the answer chatgpt provides.

There is however a so called eventstream tab – does this imply the chatgpt response download is issued after the fetch?

So i make a fetch request to “backend-api/conversation” and then wait for any signal to download the response?

What technology is used specifically? I genuinely try to understand the mechanism behind this.

MongoDB to Bigquery (batch) dataflow template – UDF not working

We are trying load our current data in mongoDB into bigquery on a scheduled basis. And currently trying to use google cloud’s dataflow service working with the MongoDB to Bigquery (batch) template with some UDF. Unfortunately I cant seem to get the UDF to work for this job using the cloud console. The job runs runs perfectly and correctly loads the entire data into bigquery but the UDF function is not applied.
Here is an example UDF I have tried below, this should just add a new string field to the data but that does not work either.

/**
 * User-defined function (UDF) to transform elements as part of a Dataflow
 * template job.
 *
 * @param {string} inJson input JSON message (stringified)
 * @return {?string} outJson output JSON message (stringified)
 */
function process(inJson) {
  const obj = JSON.parse(inJson);

  obj.udftest = "udftest";

  return JSON.stringify(obj);
}

What am I doing wrong? I have tried to just add an extra field as in the code above but that doesn’t work either, it just loads the flattened data if useroption is FLATTEN and the normal json format if useroption is NONE. The UDF function is totally disregarded and pipeline works successfully without throwing any error.

I have followed this blog post from MongoDB using the given function structure and format still to no avail. I have change the obj variable type to a normal var instead of const but it still did not work. Followed the bigquery documentation and that did not help either.