When I open some web pages, they may jump to another web page automatically after a while. For example, if you open https://list.jd.com/list.html?cat=670,677,688 it will jump to cfe.m.jd.com/…, then further jump to passport.jd.com that asks you to login. I think on the page list.jd.com/…, there must be a statement like window.location.href=...that causes the jump. But where is the statement? How can I find the statement in a systematic way? I mean I can press F12 and set a breakpoint on that statement then refresh the page to stop at that statement.
Category: javascript
Category Added in a WPeMatico Campaign
Repeatedly getting 404 errors while trying to submit React form
I’m working on a forum using Express/React and I’m having trouble submitting the data from the form to the database. For now I’m just trying to add topic titles to its own MongoDB collection but in the future I plan on adding more message content. I have no idea why it’s not working. I have another similar form for registering account and it’s working just fine. When I console.log(title) it shows the title so I know I’m getting the data but I’m stuck with getting that data to save to the database after debugging for several days. Again, what I’m trying to do is make a form and enter the title of a topic and save that data to a database so that users can enter a topic and (in the future) make their own posts inside the topic.
This is the error code I’m getting when I hit submit.
POST http://localhost:3000/topic/create 404 (Not Found)
Here is my url that the form is located under.
http://localhost:3000/topic/create
Here is my server.js route code.
app.use("/topic", topicRoutes);
Here’s my forumApiSlice
const TOPIC_URL = "/topic";
export const forumApiSlice = apiSlice.injectEndpoints({
endpoints: (builder) => ({
create: builder.mutation({
query: (data) => ({
url: `${TOPIC_URL}/create`,
method: "POST",
body: data,
}),
}),
}),
});
Here is my form code.
const CreateTopic = () => {
const [title, setTitle] = useState("");
const [author, setAuthor] = useState("");
const navigate = useNavigate();
const dispatch = useDispatch();
const [create] = useCreateMutation(); // forumApiSlice
const { userInfo } = useSelector((state) => state.auth); // to get the author of the topic
const submitHandler = async (e) => {
e.preventDefault();
try {
const res = await create({ title, author }).unwrap();
dispatch({ ...res });
navigate("/");
} catch (err) {
toast.error(err.error);
}
};
return (
<FormContainer>
<h1>Create Topic</h1>
<Form onSubmit={submitHandler}>
<Form.Group className="my-2" controlId="title">
<Form.Label>Title</Form.Label>
<Form.Control
type="text"
placeholder="Enter Title"
onChange={(e) => setTitle(e.target.value)}
></Form.Control>
</Form.Group>
<Form.Group className="my-2" controlId="author">
<Form.Label></Form.Label>
<Form.Control
type="text"
value={userInfo.name}
onChange={(e) => setAuthor(e.target.value)}
></Form.Control>
</Form.Group>
<Button type="submit" variant="primary" className="mt-3">
Create Topic
</Button>
</Form>
</FormContainer>
);
};
And here’s my backend code.
router.post("/create", createTopic);
const createTopic = asyncHandler(async (req, res) => {
const { title, author } = req.body;
const topicExists = await Topic.findOne({ title });
if (topicExists) {
res.status(400);
throw new Error("Topic Already Exists!");
}
const topic = await Topic.create({
title,
author,
postCount: 1,
});
if (topic) {
res.status(201).json({
_id: topic._id,
title: topic.title,
author: topic.author,
postCount: topic.postCount,
});
} else {
res.status(400);
throw new Error("Invalid Topic Data");
}
});
I want to embed teams chat interface in the team’s tab application. Can someone please help me with this [closed]
I want to embed the Microsoft team chat interface in the Microsoft team’s tab application. Can someone please help me with this
I tried using Fluent UI, but didn’t find it very useful. As it requires a lot of customization, and it seems not supporting Android and ios verions
How can I embed HTML content with specific widgets in react/js
We are working on a large social network site built with a micro frontend architecture in React and utilize some private libraries. Our goal is to enhance user engagement by allowing users to embed HTML content, similar to Twitter, and include specific widgets (e.g., comments with details like the number of likes).
I’m seeking guidance or examples on how to kickstart the implementation of this functionality. Any references or advice on how to approach this within our tech stack would be greatly appreciated.
Thank you!
Search bar is Not working in flatlist React Native…?
I’m being struggling a couple of days with search bar in my app, the problem is that when I search with particular name of products the products with that name show up but when I clear the search bar the entire products disappear not showing up after clearing search bar?
Here is my Code:
const Home =()=>{
// State
const [categories, setCategories] = useState(categoryData)
const [selected, setSelected] = useState(null)
const [productst, setProducts] = useState (ProductData)
// seach function
function handleSearch(text){
const filterData = productst.filter((item)=>{
return item.name.toLowerCase().includes(text.toLowerCase())
})
setProducts(filterData)
}
function renederHeader(){
return(
//Search Input
<View style={{ marginTop:SIZES.margin,}} >
<TouchableOpacity
onPress={()=>{}}
style={{
flexDirection:'row',
alignSelf:'center',
}}>
<TextInput
placeholder=" Find Your Favourite..."
placeholderTextColor={COLORS.lightGrey20}
// value={}
onChangeText={text=>handleSearch(text)}
/>
</TouchableOpacity>
</View>
}
function renderCategories(){
return(
<View
style={{
marginTop:20,
}}
>
<FlatList
horizontal
showsHorizontalScrollIndicator={false}
data={categories}
keyExtractor={item=>item.id}
renderItem={({item,index})=>{
return(
<TouchableOpacity
onPress={()=>onSelecteCategory(item)}>
)
My Product Data:
export const ProductData = [
{
id: 1,
name:'Coffee',
categories: [1],
image: require('../asset/images/coffee1.png'),
index: 0,
},
{
id: 2,
name:'Coffee',
categories: [1],
image: require('../asset/images/coffee2.png'),
index: 0,
},
{
id: 3,
name:'Coffee',
categories: [1],
image: require('../asset/images/coffee3.png'),
index: 0,
},
{
id: 4,
name:'Tea',
categories: [2],
image: require('../asset/images/Tea1.png'),
index: 0,
}, {
id: 5,
name:'Tea',
categories: [2],
image: require('../asset/images/Tea2.png'),
index: 0,
},
{
id: 6,
name:'Tea',
categories: [2],
image: require('../asset/images/Tea3.png'),
index: 0,
},
{
id: 7,
name:'choclate',
categories: [3],
image: require('../asset/images/choclate1.png'),
index: 0,
},
{
id: 8,
name:'choclate',
categories: [3],
image: require('../asset/images/choclate2.png'),
index: 0,
},
{
id: 9,
name:'choclate',
categories: [3],
image: require('../asset/images/choclate3.png'),
index: 0,
},
]
So, Please if anyone can help me how to search in bar and get the certain products and when I clear the search bar the all products should show up normally not disappear as it is now.
Conditional return type on TypeScript with boolean check doesn’t seem to work
Given the following code:
type OpenFileDialogReturn<TMulti extends boolean> =
TMulti extends true ? FileList | null | undefined :
TMulti extends false ? File | null | undefined :
never
type OpenFileDialog = {
(options: { multiple?: false, acceptedFileTypes?: string }): Promise<OpenFileDialogReturn<false>>
(options: { multiple: true, acceptedFileTypes?: string }): Promise<OpenFileDialogReturn<true>>
}
export const openFileDialog: OpenFileDialog = (options = { }) => {
return new Promise(resolve => {
const input = document.createElement('input')
input.type = 'file'
input.style.opacity = '0'
if (options.acceptedFileTypes) input.accept = options.acceptedFileTypes
if (options.multiple) input.multiple = true
input.addEventListener('input', () => {
if (options && options.multiple === true) resolve(input.files)
const file = input.files?.[0]
if (!file) resolve(null)
resolve(file)
})
input.click()
})
}
TypeScript is throwing an error on the last resolve(file)
Argument of type 'File | undefined' is not assignable to parameter of type 'FileList | PromiseLike<FileList | null | undefined> | null | undefined'.
Type 'File' is not assignable to type 'FileList | PromiseLike<FileList | null | undefined> | null | undefined'.ts(2345)
const file: File | undefined
I’ve tried several approaches, even wrapping everything in strict if/else blocks to make sure that TS understands that options.multiple is strict false at this point but nothing seems to work. Any help is appreciated.
Value of the select can be seen on the component. But when passing it to the server action, it does no show anymore
I am using Nextjs14 and Supabase.
I have this select where the user can choose from. I am also passing it on the formValue which will be received on the server actions as FormData. Now, on the component, I can see the data of the formValue and the barangay field is there. However, passing in on the server actions, the barangay field can no longer be seen on the server actions.
This is my reusable component named DropDownList.tsx:
import React, { Fragment, useState, useEffect } from 'react';
import { Listbox, Transition } from '@headlessui/react';
import { CheckIcon, ChevronUpDownIcon } from '@heroicons/react/20/solid';
type Props = {
options: string[];
selected: string;
onSelect: (value: string) => void;
required: boolean;
placeholder: string;
value: string;
name: string;
};
function classNames(...classes: string[]) {
return classes.filter(Boolean).join(' ');
}
const DropdownList: React.FC<Props> = ({ options, selected, onSelect, required, placeholder , value, name}) => {
// Initialize the selected state with the default selected value from the parent
const [currentSelected, setCurrentSelected] = useState<string | null>(selected);
// Update the selected state when the selected prop changes
useEffect(() => {
setCurrentSelected(selected);
}, [selected]);
return (
<Listbox value={currentSelected} onChange={(value) => {
if (value !== null) {
setCurrentSelected(value);
onSelect(value);
}
}}>
{({ open }) => (
<>
<Listbox.Label className="block text-sm font-medium leading-6 text-gray-900">
Select an option
</Listbox.Label>
<div className="relative mt-2">
<Listbox.Button className={`relative w-full cursor-default rounded-md bg-white py-1.5 pl-3 pr-10 text-left text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 focus:outline-none focus:ring-2 focus-ring-indigo-500 sm:text-sm sm:leading-6 ${required ? 'required' : ''}`}>
<span className="ml-3 block truncate">{currentSelected || placeholder}</span>
<span className="pointer-events-none absolute inset-y-0 right-0 ml-3 flex items-center pr-2">
<ChevronUpDownIcon className="h-5 w-5 text-gray-400" aria-hidden="true" />
</span>
</Listbox.Button>
<Transition
show={open}
as={Fragment}
leave="transition ease-in duration-100"
leaveFrom="opacity-100"
leaveTo="opacity-0"
>
<Listbox.Options className="absolute z-10 mt-1 max-h-56 w-full overflow-auto rounded-md bg-white py-1 text-base shadow-lg ring-1 ring-black ring-opacity-5 focus:outline-none sm:text-sm">
{/* Add a placeholder option */}
<Listbox.Option key="placeholder" value="" disabled>
{({ active }) => (
<span className={classNames('text-gray-500', 'ml-3 block truncate')}>
{placeholder}
</span>
)}
</Listbox.Option>
{options.map((option, i) => (
<Listbox.Option
key={i}
className={({ active }) =>
classNames(
active ? 'bg-indigo-600 text-white' : 'text-gray-900',
'relative cursor-default select-none py-2 pl-3 pr-9'
)
}
value={option}
>
{({ selected, active }) => (
<>
<span className={classNames(selected ? 'font-semibold' : 'font-normal', 'ml-3 block truncate')}>
{option}
</span>
{selected ? (
<span
className={classNames(
active ? 'text-white' : 'text-indigo-600',
'absolute inset-y-0 right-0 flex items-center pr-4'
)}
>
<CheckIcon className="h-5 w-5" aria-hidden="true" />
</span>
) : null}
</>
)}
</Listbox.Option>
))}
</Listbox.Options>
</Transition>
</div>
</>
)}
</Listbox>
);
};
export default DropdownList;
I am using it on this form: On this part, I can see the value barangay.
'use client'
import addWaterStation from "@/app/auth/actions/WaterStation/addWaterStation";
import React, { useEffect, useState} from "react";
import { useFormState, useFormStatus } from "react-dom";
import DropdownList from "@/components/Reusables/MyDropDownList";
import { barangay } from "./barangay";
interface FormData {
...rest of the values
barangay: string;
}
const initialState = {
message: null,
}
function SubmitButton() {
const { pending } = useFormStatus()
return (
<button type="submit" aria-disabled={pending}>
Submit
</button>
)
}
export default function WaterStationProfileForm() {
const [state, formAction] = useFormState(addWaterStation, initialState)
const [selectedBarangay, setSelectedBarangay] = useState<string>(''); // Rename the state variable
const handleBarangaySelection = (value: string) => {
setSelectedBarangay(value); //get the selected barangay
}
const [formValue, setFormValue] = useState<FormData>({
...rest of the values
barangay: "",
});
useEffect(() => {
setFormValue(prevFormValue => ({
...prevFormValue,
barangay: selectedBarangay
}))
},[selectedBarangay])
console.log(formValue, "form value") // I can see the value of barangay here
return (
<div className="container mx-auto p-4">
<form action={formAction}>
...the rest of the inputs
<DropdownList
options={barangay}
value={formValue.barangay}
selected={selectedBarangay}
onSelect={handleBarangaySelection}
required={true}
placeholder="Please select an option"
name="barangay"
/>
<SubmitButton />
</form>
</div>
);
}
My server action: On this part, the value barangay is not present anymore. Only the rest of the values shows.
Sample FormData value. The barangay is not on the name and no value:
FormData {
[Symbol(state)]: [
{ name: '$ACTION_REF_1', value: '' },
{
name: '$ACTION_1:0',
value: '{"id":"32933f3a25fdc884c208dbcbf3540cf9ccf38c62","bound":"$@1"}'
},
{ name: '$ACTION_1:1', value: '[{"message":null}]' },
{ name: '$ACTION_KEY', value: 'k3775125042' },
{ name: 'zone', value: '7' },
{ name: 'delivery_mode', value: 'Delivery and Pickup' },
{ name: 'contact_no', value: '9676832484' },
{ name: 'tel_no', value: '' },
{ name: 'remarks', value: '' }
]
} formData
Codes for the server action:
'use server'
import { createServerComponentClient } from "@supabase/auth-helpers-nextjs"
import { revalidatePath } from "next/cache";
import { cookies } from "next/headers"
export default async function addWaterStation(prevState: any, formData: FormData): Promise<{ message: string }> { const supabase =createServerComponentClient({cookies})
const {data: {user}} = await supabase.auth.getUser();
const formDataAddress = `${formData.get('buildingNumber')}, ${formData.get('street')}, ${formData.get('zone')}`
console.log(formData, "formData")
try{
const station_name = formData.get('name')
const {data, error} = await supabase.from('water_refilling_station')
.insert({
...rest of the inputs here
barangay,
}).select()
if(error){
return {message: `${error.message} - unable to save`}
}
revalidatePath('/water_station')
return { message: `Succesfully added the data` }
}catch(e){
return {message: "Failed to submit the form."}
}
}
How to load SCROM 2004 with cmi.location(user’s last location)
I have integrated https://github.com/gabrieldoty/simplify-scorm to show the SCROM file content and it’s working fine.
The system displays SCORM courses effectively, but it doesn’t retain user progress and input data. Our progress data is stored externally, and we need to load this JSON data into the SCORM content during page loading. This project is based on SCORM 2004, aiming to synchronize and save user progress seamlessly within the course materials.
here is the code sample
function setupScormApi() {
API_1484_11.Initialize = Initialize;
API_1484_11.Commit = Commit;
API_1484_11.Terminate = Terminate;
API_1484_11.GetValue = GetValue;
API_1484_11.SetValue = SetValue;
API_1484_11.GetErrorString = GetErrorString;
API_1484_11.GetDiagnostic = GetDiagnostic;
API_1484_11.GetLastError = GetLastError;
API_1484_11.loadFromJSON = loadFromJSON;
}
how to enable a vertical scroll in vuejs with highlight text
i want the use to scroll only the content inside the sticky section of the parent element and also want the user to scroll only one item of the loop per mouse scroll and highlight the active section with opacity 1 and non active with opacity 0.5
<div
id="stickyParent"
class="tw-hidden sticky-parent tw-pb-[4.5rem] lg:tw-block tw-relative tw-h-[300vh]"
>
<div
id="sticky"
class="tw-sticky tw-top-[6.5rem] tw-h-auto tw-container main tw-overflow-auto"
>
<hr
class="tw-absolute tw-h-full tw-left-[50%] tw-border-[0.1px] tw-opacity-[0.5]"
/>
<div
v-for="(item, index) in items"
:key="index"
class="tw-mb-[4.5rem] item"
>
<div
:class="[
' tw-flex tw-gap-[4rem]',
{
' tw-flex-row tw-text-right ': index % 2 === 0,
' tw-flex-row-reverse tw-text-left': index % 2 !== 0,
},
]"
>
<div class="tw-flex tw-flex-col tw-flex-1 tw-gap-[1.5rem]">
<div class="header-3">
<span v-html="item.desktoptitle"></span>
</div>
<div class="sub-h3-regular">
<p
v-for="(list, listIndex) in item.description"
:key="listIndex"
>
{{ list }}
</p>
</div>
</div>
<div class="tw-flex-1" :class="{ 'tw-relative': index % 2 !== 0 }">
<img
:src="item.image"
alt="development-service-image"
class=""
:class="{
'tw-absolute tw-right-0': index % 2 !== 0,
}"
loading="lazy"
/>
</div>
</div>
</div>
</div>
</div>
any idea how can it be achieved..
Using await with map and reduce [duplicate]
How can I use await inside array map. My code is as below
...gridSelectedContracts
.map((gridSelectedContract) => {
i++;
const arr = [];
arr.push(
new Paragraph({
text: `${gridSelectedContract.Year.Title} PERFORMANCE CONTRACT`,
heading: HeadingLevel.HEADING_1,
}));
arr.push(
new Paragraph({
text: `Performance Contract between ${gridSelectedContract.Employee.Title} and Boubyan Bank, whereby it is agreed as follows:`,
style: "normalPara"
}));
arr.push(
new Paragraph({
text: "In pursuit of achieving the business objectives of Boubyan Bank, I commit myself to achieve the Key Performance Indicators and outcomes contained in my Performance Contract.",
style: "normalPara"
}));
arr.push(
new Paragraph({
text: `This Agreement signed 30 October ${gridSelectedContract.Year.Title}, will be valid for the year ending 31st December ${gridSelectedContract.Year.Title}, and is subject to review on a quarterly basis.`,
style: "normalPara"
}));
const userKPI = await getUserKPI(gridSelectedContract.Id, selectedContract); // Error
arr.push(userKPI);
if (i < countSelectedContracts) {
arr.push(
new Paragraph({
pageBreakBefore: true
}));
}
return arr;
})
.reduce((prev, curr) => prev.concat(curr, []))
Can somebody help me how can I use await inside map
Is it possible to Integrate React Js code in an existing WordPress Webiste?
I am working on a project in which I created a ChatBot using React Js. Now, I want to implement/deploy my ChatBot in an existing WordPress website. I use iframe tag to display my ChatBot but the problem is iframe didn’t display my ChatBot perfectly as it takes complete web page which causes problem. Can anyone tell me how to implement or deploy my ChatBot in WordPress webite? I wants only ChatBot in WordPress webiste (in every signle page) in a same size, same location. Please suggest me solutions.
- I have tried many solutions like I use 000Webhost to deploy build files of my ChatBot by running this command
npm run buildand, then I try to use 000Webhost url in iframe. - I also explore its other solution. I found that using WP-API will be very helpful but I found only JWT Authentication for WP REST API and I don’t know how to properly use it in WordPress webiste to deploy my ChatBot.
I am waiting for your kind responses.
Thanks.
How to set a request proxy for requests sent by the server in nextjs middleware
In my project development, account services need to distinguish between formal and testing environments, which have the same domain name and different IPs. In the development environment, I need to initiate authentication requests to the test environment of the account server in the middleware. Prior to this, I had completed this task by modifying the local host file. Now, I want to complete this task through code configuration or request proxies. In my other project, I used the Whistle proxy and Axios proxy function to forward 8899 to complete this task, but in the nextjs project’s middleware, Axios cannot be used, so I don’t know how to implement similar functions.
I have tried to retrieve the proxy function of fetch, but I have not found any valid information
NodeJs “EACCES” error from spawnSync on cpanel/whm with passenger
I run a simple NodeJs app on my server and i’m can’t solve a problem i encountred today.
The server is running CPannel/WHM and use passenger to display multiple node application. In one of them i use the npm package require-from-url. In localhost with the exact same parameters (same code, same url), no problem, but when i send my app on server, i can’t retrieve the content of the url.
When i check further, i get an Error: spawnSync node EACCES. Here is the function that failed on server side:
var parse = require("url").parse;
var resolves = require("./resolves.js");
var spawnSync = require('child_process').spawnSync;
var options = {
cwd : __dirname,
stdio: ['ignore','pipe','ignore']
};
var requireFromString = require("./requireFromString.js");
function sync(urlString) {
var url = parse(urlString),
href = url.href;
if(!resolves[href]) {
var returns = spawnSync('node', ['fetch.js', href], options); // the error occurs here
var err_str_filename = JSON.parse(returns.stdout.toString());
if(err_str_filename[0]) throw new Error(err_str_filename[0]);
resolves[href] = requireFromString(err_str_filename[1], err_str_filename[2]);
}
return resolves[href];
}
Here is the content of my returns variable that failed:
{
error: Error: spawnSync node EACCES
at Object.spawnSync (node:internal/child_process:1124:20)
at spawnSync (node:child_process:876:24)
at sync (/my/path/to/node_modules/require-from-url/sync.js:16:23)
at Object.<anonymous> (/my/path/to/app.js:22:24)
at Module._compile (node:internal/modules/cjs/loader:1241:14)
at Module._extensions..js (node:internal/modules/cjs/loader:1295:10)
at Module.load (node:internal/modules/cjs/loader:1091:32)
at Module._load (node:internal/modules/cjs/loader:938:12)
at Module.require (node:internal/modules/cjs/loader:1115:19)
at Module.require (/opt/cpanel/ea-ruby27/root/usr/share/passenger/helper-scripts/node-loader.js:80:25) {
errno: -13,
code: 'EACCES',
syscall: 'spawnSync node',
path: 'node',
spawnargs: [
'fetch.js',
'https://url.com/to/the/distant/file.js'
]
},
status: null,
signal: null,
output: null,
pid: 0,
stdout: null,
stderr: null
}
I guess is question of passenger or node configuration. I’ve tried many things, nothing works. Any help or idea will be really appreciated.
How to display a translated string on two rows
I have to make a simple react component which displays a translated string on two rows, second row must start always with the third word.
example:
<div className="parent">
<span>{t('myText')}</span>
</div>
myText value from the translation file is = “Text that I want to display”
I tried using this “Text that n I want to display” but didn’t work.
which would be the best and the simplest way to solve this?
FInding PPI of an Image during image uploads, if EXIF metadata is absent
How to add a backup measure in javascript to get the Pixel Per Inch info of an image if PPI is unavailable in EXIF Data
I have a tool in frappeframework that permits image uploads by checking, the width, height and filesize of an image in js code.