A code to repeat my function / keep displaying the text in javascript

I would like to display the text in the browser again and again in a new line every time, however there is only the first line of text appearing. How this code should be corrected? Besides, I know that setinterval() is to repeat a function, I’d like to ask how can it be used in this code? Thank you very much!

var text = document.getElementById('text');
text.innerText = create_random_string(20);


function create_random_string(string_length){
  var random_string = '';
  var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
  for (var i, i = 0; i < string_length; i++) {
     random_string += characters.charAt(Math.floor(Math.random() * characters.length));
  }
  return random_string; 
}

document.write (
  create_random_string(20) + "<br>",
  create_random_string(20) + "<br>",
  create_random_string(20) + "<br>",
  create_random_string(20) + "<br>",
);

Show tooltip when user moves mouse on column name of bootstrap-vue table

I have a bootstrap-vue table that looks like this;

enter image description here

Here’s the code for the table;

<template>
  <div>
    <b-table striped hover :items="items" :fields="fields"></b-table>
  </div>
</template>

<script>
  export default {
    data() {
      return {
        // Note 'isActive' is left out and will not appear in the rendered table
        fields: [
          {
            key: 'last_name',
            sortable: true
          },
          {
            key: 'first_name',
            sortable: false
          },
          {
            key: 'age',
            label: 'Person age',
            sortable: true,
            // Variant applies to the whole column, including the header and footer
            variant: 'danger'
          }
        ],
        items: [
          { isActive: true, age: 40, first_name: 'Dickerson', last_name: 'Macdonald' },
          { isActive: false, age: 21, first_name: 'Larsen', last_name: 'Shaw' },
          { isActive: false, age: 89, first_name: 'Geneva', last_name: 'Wilson' },
          { isActive: true, age: 38, first_name: 'Jami', last_name: 'Carney' }
        ]
      }
    }
  }
</script>

This is what I want to do. When user moves his mouse to First Name column name cell, I want to show a tooltip that says “Click to sort First Name”.

I am using vue v2.6

Caused by: netscape.javascript.JSException: ReferenceError: Can’t find variable: lat

i have a javaFx webview map with ” open Street Map ” , i want to get the latitude and longitude from js to Java , but it shows me this error :

Caused by: netscape.javascript.JSException: ReferenceError: Can't find variable: lat

Java

       url = this.getClass().getResource("map/index.html");
        webengine.load(url.toString());

        String fullName = (String) webview.getEngine().executeScript("lat");

        System.out.println("Lat: " + fullName);

Java Script

let lat;
 let lon;
map.on('click', function (e) {
    lat=e.latlng.lat;
    
          lon =  e.latlng.lng;
          
          lati=document.getElementById('latitude').textContent = lat;
         loni=document.getElementById('longitude').textContent = lon;

});

i want to get the lat from js to java , Anyy Solution ?

Req.body from the database is returning empty object when trying to delete user

I’m trying to delete an user, but the problem is that I’m trying to do that by taking the user id from the req.body in the database, I have the following logic in the redux actions and I think here is a problem with the order of the params:

export const deleteUser = (userId) => async (dispatch, getState) => {
  dispatch({ type: USER_DELETE_REQUEST, payload: userId });
const {
    userSignin: { userInfo },
  } = getState();
  try {
    const { data } = await Axios.delete(
      "http://localhost:3030/v1/user/userProfile/deleteUser",
      {
        userId
      }, 
      {
      headers: { Authorization: `Bearer ${userInfo.token}` },
     });
    dispatch({ type: USER_DELETE_SUCCESS, payload: data });
  } catch (error) {
    const message =
      error.response && error.response.data.message
        ? error.response.data.message
        : error.message;
    dispatch({ type: USER_DELETE_FAIL, payload: message });
  }
};

When I’m doing console logging the req.body in the backend is empty, what can I do?

Uncaught TypeError: Failed to execute ‘webkitGetUserMedia’ on ‘Navigator’: At least one of audio and video must be requested

I am trying to do a simple audio video capture of the page in Chrome browser via chrome extension I am building. I am running the following code in a content script.

I don’t understand why it is struggling to accept my config, I’ve included both audio and video yet it still complains that

Uncaught TypeError: Failed to execute 'webkitGetUserMedia' on 'Navigator': At least one of audio and video must be requested
    at chooseDesktopMedia 

here is the code I tried:

chooseDesktopMedia();

function chooseDesktopMedia(){
    navigator.webkitGetUserMedia(
        ["screen"]
    , function onSuccess(stream) {
        showScreenShare(
            {
                audio: true,
                video: {
                    mandatory: {
                        chromeMediaSource: 'desktop',
                        chromeMediaSourceId: streamId
                    }   
                }   
            }            
        );
    }, function onError(e) {
        console.error(e);
        alert('Failed to get user media.');
    });
}

function showScreenShare(conf){
    var ve = document.getElementById("screen-share");

   navigator.mediaDevices.getUserMedia(conf)
    .then(function(stream){
        var url = window.URL.createObjectURL(stream);
        ve.src = url;
    })
    .catch(function(e){
        console.log(e);
        alert(e);
    });

}

Reactjs toggle object state

I want to toggle true/false when I click on each elements, but it reset after click on other element, example: if you click aaa it toggle between true/false but if you click bbb , aaa reset to false

class Search extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
    data: {aaa: false,bbb: false,ccc: false}
    }

  }
  
    Handler = (which, status) => {
       this.setState({data: {...this.state.data, [which]: !this.state.data[which]} })
       console.log(this.state.data)
    }
  
  render() {
    return (
      <ul>
      <li onClick={()=>this.Handler('aaa')}>{this.state.data.aaa ? 'true' : 'false'}</li>
      <li onClick={()=>this.Handler('bbb')}>{this.state.data.bbb ? 'true' : 'false'}</li>
      <li onClick={()=>this.Handler('ccc')}>{this.state.data.ccc ? 'true' : 'false'}</li>
      </ul>
    )
  }
}

ReactDOM.render(<Search />, document.querySelector("#app"))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/reactstrap/6.3.1/reactstrap.full.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" />

<div id="app"></div>

What I have done wrong?

Next.js Vercel CORS header ‘Access-Control-Allow-Origin’ missing

Before you mark this as duplicate, you should know that have tried using the three methods from adding cors middleware, using vercel.json, and next.config.js to set the header, yet I keep getting the same error. I am using the next.js API for the backend and with the front end, I use custom Axios with the base URL similar to the vercel default link. This works locally but when I deploy it to vercel , I get the cors error above

vercel.json
{
    "headers": [
      {
        "source": "/api/(.*)",
        "headers": [
          { "key": "Access-Control-Allow-Credentials", "value": "true" },
          { "key": "Access-Control-Allow-Origin", "value": "*" },
          { "key": "Access-Control-Allow-Methods", "value": "GET,OPTIONS,PATCH,DELETE,POST,PUT" },
          { "key": "Access-Control-Allow-Headers", "value": "X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version" }
        ]
      }
    ]
  }

next.config.js

const { withPlaiceholder } = require("@plaiceholder/next");

module.exports = withPlaiceholder({ 
  images: {
    domains: ["images.unsplash.com", 'i.ibb.co', 'wpbingosite.com', 'www.chicintuition.com'],
  },
   async headers() {
    return [
      {
        source: "/api/:path*",
        headers: [
          { key: "Access-Control-Allow-Credentials", value: "true" },
          { key: "Access-Control-Allow-Origin", value: "*" },
          { key: "Access-Control-Allow-Methods", value: "GET,OPTIONS,PATCH,DELETE,POST,PUT" },
          { key: "Access-Control-Allow-Headers", value: "X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version" },
        ]
      }
    ]
  }
});

export default function initMiddleware(middleware) {
  return (req, res) =>
    new Promise((resolve, reject) => {
      middleware(req, res, (result) => {
        if (result instanceof Error) {
          return reject(result)
        }
        return resolve(result)
      })
    })
}

const cors = initMiddleware(

  Cors({

    methods: ['GET', 'POST', 'OPTIONS', 'PUT', 'DELETE'],
  })
)

export default cors

and then in for the front end


let url 

if (process.env.NODE_ENV === "development") {
  url = config.urlDev
} else {
  url = config.urlProd
}

interface CustomRequestProps extends AxiosRequestConfig {
  headers: {
    authorization: string
  }
}


export const apiCall = Axios.create({
    baseURL: url,
});

apiCall.interceptors.request.use(authRequestInterceptor)

async function authRequestInterceptor(config: AxiosRequestConfig) {
  const token = await auth.currentUser?.getIdToken(true)
  let  customConfig: CustomRequestProps = {
    ...config,
    headers: {
      authorization: ''
    }
  }
  if (token) {
    customConfig.headers.authorization = `${token}`;
  }
  return customConfig;
}

How to fetch data and display comments from user posts using the JSONPlaceholder API

I’m trying to display comments from user posts using the JSONPlaceholder API.

Functionality:
Posts load from https://jsonplaceholder.typicode.com/posts and are displayed on the page.
The page displays the title and body properties from the post.
When a post’s body is clicked, the post’s comments are fetched from https://jsonplaceholder.typicode.com/posts/${postId}/comments.

The page displays the body property of all the comments for a post on the page after the post is clicked.

Posts have this structure:
{
“userId”: 1,
“id”: 1,
“title”: “sundent occaecati excepturi optio reprehenderit”,
“body”: “quia et recusandae consequuntur expedita et cumnreprehenderit molestiae ut ut quas totamnnostrum rerum est autem sunt rem eveniet architecto”
},
The post should display the title and body
Each post has 5 comments
A post’s comments have the following structure:
{
“postId”: 1,
“id”: 4,
“name”: “alias odio sit”,
“email”: “[email protected]”,
“body”: “non et leniti ut occaecati”
}

A post’s comments should only show after the post body is clicked.
All information can be displayed on the same page

=================================================

my code in App.js

import React, { useEffect, useState } from "react";
import PostDetail from "./PostDetail";

function App() {
  const [posts, setPosts] = useState([]);

  useEffect(() => {
    fetch("https://jsonplaceholder.typicode.com/posts?userId=1")
     .then((response) => response.json())
     .then(setPosts)
     .catch((error) => { 
    console.log(error)
     });
 }, []);

const listPosts = posts.map(post => <li>{post.tittle}</li>);

return (
<div className="App">
 <PostDetail
        />
    </div>
  );
}

export default App;

===========================================
code in postDetail.js

import React, { useEffect, useState } from "react";

function postDetail() {
  const [posts, setPosts] = useState([]);

useEffect(() => {
fetch(`https://jsonplaceholder.typicode.com/posts/${postId}/comments`)
  .then((response) => response.json())
  .then(setPosts)
  .catch((error) => {
    console.log(error)
  });
  }, []);
  const listPosts = posts.map(post => {posts.tittle});

  return (
    <div className="App">
   <button type="button" onClick={() => setAllData({...allData, currentUser : user})}>
        {user.name}
      </button>
   </div>
 );
}


Screenshot of errors:

  [1]: https://i.stack.imgur.com/9gss7.png

How to hide/invisible a button in odoo helpdesk using js

In Odoo version 15 I created a Js cod Based on the button Accept and Deny and I created a boolean field in res users model. The workflow is: if the user clicks the Accept button the boolean field makes True and clicks the Denay button it change to False state. The Functionality is working well. Currently, the issue am facing is both buttons are showing on page refresh time. How to solve this … Actually I want to show only One button based on the user availability( based on the Boolean field)

how to pass parameters in Asynccall?

I have this javascript api call

api.call("Get",{"typeName":"LogRecord",
               "resultsLimit":10,
               "search":{
               "fromDate":new Date().toISOString()
            }});

Now i need to call the same api using C# with same parameters. This is how my C# code looks like –

public async Task<List<LogRecord>> GetLogRecord(API api, ILogger log)
        {
            List<LogRecord> data = new List<LogRecord>();
            try
            {
                api.Timeout = 3600000;
                var type = "LogRecord";
                
                Dictionary<string, object> parameters;
                Dictionary<string, object> date1 = new Dictionary<string, object>{};
                date1.Add("fromDate", new DateTime().ToString());
                parameters = new Dictionary<string, object>{};
                parameters.Add("typeName", type);
                parameters.Add("resultsLimit", 10);
                parameters.Add("search", date1);
                data = await api.CallAsync<List<LogRecord>>("Get", typeof(LogRecord), parameters,default);
                //{
                //    parameters
                //});
            }
            catch (Exception ex)
            {
                log.LogInformation(ex.Message.ToString());
            }
            return data;
        }

But i am getting an exception : “Error getting json response. HttpStatusCode: OK
What i am doing wrong i am not getting it. Please Help!

How to allow upload of large files to linode server using node js multer

Hi guys i got a linode server and am trying to make a file upload through an endpoint to my backend server hosted on my linode server, when i upload files less than 1-2 mb it works but above that it doesn’t, i tried testing same upload functionality using heroku it worked, but it doesn’t work on my linode server instead my axios returns a “network error” please is there any config i need to do to allow large file upload am using react axios, node js and multer.

my code

        try{

        const formData = new FormData();
        formData.set('txt', textValue)
        formData.set('post_for', PostFor)
        fileList.forEach(element => {
            formData.append('files', element)
        })

        setloading(true)
        setError();
        
        axios.post(`${ENDPOINT}/feed/`, formData,{
            headers:{token:localStorage.token,"Content-Type":"multipart/form-data"},
            onUploadProgress: (data) => {
                setProgress(Math.round(100 * (data.loaded / data.total)));
              },
        }).then(res => {
            if(res.data){
                setloading(false)
                setFileList([])
                setpreviewImage([])
                setpreviewVideo([])
                setText('')
                setError();
                socket.emit('refresh_feed')
                message.success('feed uploaded successfully')
                setTimeout(()=>{
                    setProgress()
                },6000)             
     
         }else if(res.error){
            setloading(false)
             message.error(res.error)
         }
         }) .catch((error) => {
            const code = error
            switch (code) {
              case "FILE_MISSING":
                setError("Please select a file before uploading");
                setloading(false)
                break;
              case "LIMIT_FILE_SIZE":
                setError("File size is too large. Please upload files below 1MB!");
                setloading(false)
                break;
              case "INVALID_TYPE":
                setError(
                  "This file type is not supported. Only .png, .jpg, and .jpeg files are allowed"
                );
                setloading(false)
                break;
              default:
                setError("Sorry, something went wrong");
                setloading(false)
                break;
            }
          });
        }catch (error) {}
    }


const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, `./src/uploads`)
  },
  filename: function (req, file, cb) {
    // if(file.mimetype === 'video/mp4' || file.mimetype ===  'audio/mpeg'){
    //   return cb(null, Date.now() + '.mp3')
    // }
     cb(null, Date.now() + path.extname(file.originalname))
  }
})
  
  export const upload = multer({ storage: storage })