How can I get post content from WordPress API and maintain or recreate positioning?

I’ve created a Next.js app and it’s my intention to pull post data from my WordPress.com site via the public WordPress API. I’ve gotten the HTML content of my posts just fine at this endpoint:

https://public-api.wordpress.com/wp/v2/sites//posts

but aside from minimal inline styling there’s no way to recreate the structure of the original post – ie, columns, galleries, grids, blocks, etc.

I can of course apply my own CSS to adjust fonts, colors, responsiveness, etc, but don’t I need the positioning styling to make sure that the post is as the original author intended it to be? Columns in the original post, for example, are not respected because the class names that denote them in the API response don’t exist anywhere in my CSS. I could conceivably use these class names to recreate similar element positioning, but this seems like an awkward and messy approach.

I’ve tried manually adding the stylesheets from the post’s page, but still the styling from the page did not appear to match the class names from the API post content.

I expected that the API response would include some way to at least recreate the original structure of the content from the post so that my app can position the content similar to how the author did. Or is this just not possible? Thanks in advance for any help!

Elements in different routes are inaccessible in a JavaScript single page application

I have a route "/login" which has 2 input fields for email and password, and also there’s a button to click after filling up the fields, however, I have to add an event listener for the fields if there’s an Enter Keypress because I want the user to send the data by pressing enter rather than mouse click manually on the button, and I don’t want to use forms.

Now, when I add that event listener in the home page as shown below, it says element is null since it cannot see it because it still didn’t load the content of "/login" to the home page.

Any way to access those elements in different routes?

Here’s the code for the index page "/":

<!DOCTYPE html>
<html>
    <head>
        <title>Vanilla SPA Router</title>
    <meta charset="UTF-8" />
    <link rel="stylesheet" href="css/styles.css" />
    <link href="https://cdn.jsdelivr.net/npm/@mdi/[email protected]/css/materialdesignicons.min.css" rel="stylesheet" />
</head>

<body>
    <div id="root">
        <nav id="main-nav" class="sidebar">
            <a href="/" onclick="route()">Home</a>
            <a href="/about" onclick="route()">About</a>
            <a href="/lorem" onclick="route()">Lorem</a>
            <a href="/login" onclick="route()">login</a>

        </nav>
        <div id="main-page"></div>
    </div>

<script> 
    // adding event listener here for id elements password
    var input = document.getElementById("password");

    input.addEventListener("keypress", function(event) {
       if (event.key === "Enter") {
          event.preventDefault();
          document.getElementById("login_btn").click();
       }
    }); 

// the login() will be called by login_btn, but I didn't include 
// it for this question since it's unnecessary
</script>
    <script src="router.js"></script>
</body>

The code for the login page "/login" :

<input type="email" id="email" placeholder="email" />  
<input type="password" placeholder="password" id="password" />
              
<button onClick="login()" id="login_btn" className="btn btn-primary">Login</button>

Javascript code for routing:

const route = (event) => {
    event = event || window.event;
    event.preventDefault();
    window.history.pushState({}, "", event.target.href);
    handleLocation();
};

const routes = {
    404: "/pages/404.html",
    "/": "/pages/index.html",
    "/about": "/pages/about.html",
    "/lorem": "/pages/lorem.html",
    "/login": "/pages/login.html",

};

const handleLocation = async () => {
    const path = window.location.pathname;
    const route = routes[path] || routes[404];
    const html = await fetch(route).then((data) => data.text());
    document.getElementById("main-page").innerHTML = html;
};

window.onpopstate = handleLocation;
window.route = route;

handleLocation();

Ajax doesn’t work on mobile unless using www. prefix

I have a web page that uses Ajax and it works great on the desktop using domain.com or www.domain.com.
It also works great on mobile, as long as I use the www.domain.com URL.

When accessing the naked domain from mobile everything works except the “ajax button”. I added a alert() in the onclick event and it works, but won’t go on to call the Ajax function (doesn’t even get to the function – I added an alert() in there, too, but it never fires).

I am using IIS6 and have multiple identities defined for the website (for domain.com as well as www.domain.com). They both work, but the function that calls Ajax only works (on mobile) if the www is in front.

I am retrieving a local file with the Ajax call.

I have found lots of solutions to remap naked to www, but I don’t seem to have any URL rewrite/redirect functionality, I don’t have a web.config file, etc. being on IIS6.

I would like to support either URL being entered into a browser.

When using mobile, the button just seems “dead” when using the naked domain.

Find all firestore document with spesific range

I have document in Firestore that has “from” and “to” fields.
I want to find all documents that are touching the given range
for example:

Doc 1
from: 2
to: 4

Doc 2
from: 4
to: 8

Doc 3
from: 7
to: 10

Doc 4
from: 3
to: 5

Doc 5
from: 1
to: 2

Range
from: 3
to: 6

So the result is: Doc 1, Doc 2, Doc 4

Is there any way to do this in Firestore? I’ve provided the image for better understanding

Example

I’ve tried this code

.where('from', '>=', 3)
.where('to', '<=', 6)

But the problem is, if one of the conditions is not fulfilled, then the document will not included

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?