How do I successfully make a POST request from port 5500 to 3000?

I’m quite new to working with full stack. I’m attempting to send JSON data to my express app from AngularJS.

My current setup is: it’s running on Port 5500 with the VS Code Live Server Extension, with the express app open on port 3000. I keep getting a 405 error when attempting to make the post request and I’m really unsure. I’ve tried to adjust the URL and I keep getting things like CORS errors and I’m lost.

Express:

const express = require('express')
const app = express()
const port = 3000

app.get('/', (req, res) => {
    console.log("Request.");
    res.send('Hello World!')
  })
  
  app.post('/test', function(req, res) {
    console.log('Processing request...');
    res.sendFile('/success.html');
});

  app.listen(port, () => {
    console.log(`Example app listening on port ${port}`)
  })

Angular

$scope.submit = function() {

      // create json file with the study set
      var questions = document.getElementsByClassName("question-text");
      var answers = document.getElementsByClassName("answer-text");
      
      // add form validation
      for (let i = 0; i < answers.length; i++) {
        $scope.set[i] = {
          "question":questions[i].innerHTML,
          "answer":answers[i].innerHTML,
        }
      }

      alert(JSON.stringify($scope.set));
      var studySet = JSON.stringify($scope.set);

      $http.post('/test', studySet).then(function(response) {
        console.log(response);
      });
      

      // send the data to the database
    }

Successs.html doesn’t exist either but I can’t even get a response so my main priority is to find out how I can get this JSON into the server to connect to Node.js

Thank you for your help! I really need it.

TypeError: (intermediate value) is not a function

so I’m currently making a Discord bot using Discord.JS V13.

I keep getting this error when I run the node index.js command

TypeError: (intermediate value) is not a function
    at module.exports (C:UsersmyUserOneDriveDesktopGreen Hosting Discord botHandlersEvents.js:10:5)

I don’t know why it is doing this. The code is:

const { Events } = require("../Validation/EventNames");
const { promisify } = require("util");
const { glob } = require("glob");
const PG = promisify(glob);
const Ascii = require("ascii-table");

module.exports = async (client) => {
    const Table = new Ascii("Events Loaded")

    (await PG(`${process.cwd()}/Events/*/*.js`)).map(async (file)=>{
        const event = require(file);

        if(!Events.includes(event.name) || !event.name) {
            const L = file.split("/");
            await Table.addRow(`${event.name || "MISSING"}`, `⛔ Event name is either invalid or missing: ${L[6] + "/" + L[7]}`)
            return;
        };

        if(event.once){
            client.once(event.name, (...args)=>event.execute(...args, client));
        } else {
            client.on(event.name, (...args)=>event.execute(...args, client));
        };

        await Table.addRow(event.name, "✔ SUCCESSFUL")
    });

    console.log(Table.toString());
};

If you could help me, that would be amazing. Thank you.

Make arr of objects with the same key javascript

I have arr

let arr = [ 
    {tags: {x: 2, y: 12}}, 
    {type: {x: 23, y: 44}}, 
    {order: {x: 5, y: 1200}}, 
]

and need (the same key, but value must come from current x)

let arr = [ 
  {tags: 2}, 
  {type: 23}, 
  {order: 5} 
] 

what I try

arr.map(({ k, v }) => { [k]: v.x });

Please about help!!

POST request in React in a for loop

So Im trying to POST multiple times, since in my database Workout has many exercises and on the Workout Volume table every exercise from the Workout table has it’s own sets, reps, weight. With this method I can only POST once and then I get an error. How can I POST request multiple times, with one click from the user?

const onSubmit =  (data) => {
//POST request on workout table
        ...
        fetch(`${BASE_URL}/workouts`, {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify(data)
        }).then(async() => {
        //post request on Workout-Volume table
            let requests = [];
            
        //some logic to split all the entered values into an arrays
            const submittedSets = inputFields.map(exercise => exercise.sets.split(','))
            const submittedReps = inputFields.map(exercise => exercise.reps.split(','))
            const submittedWeight = inputFields.map(exercise => exercise.weight.split(','))

            for (var i = 0; i < inputFields.length; i++) {
                
                data.workout_id = data.id
                data.exercise_id = exercises.find(exercise => exercise.exercise_name === submittedExercises[i].toString()).id
                data.sets = submittedSets[i]
                data.reps = submittedReps[i]
                data.weight = submittedWeight[i]
                console.log(data.exercise_id)

                requests.push(
                    fetch(`${BASE_URL}/workout-volume`, {
                        method: "POST",
                        headers: { "Content-Type": "application/json" },
                        body: JSON.stringify(data)
                    }).then(async (response) => {
                        const body = await response.text();
                        if (response.status !== 200) throw Error(body.message);
                        return Promise.resolve(true);
                    }).catch((e)=>{
                        console.error('there was an error:', e.message)
                        return Promise.resolve(false);
                    })
                )
            }
            await Promise.all(requests).then(() => {
                console.log('done')
    
                //     navigate('/workouts')
            })
        })
    }

What I get:

there was an error:
overrideMethod  @   react_devtools_backend.js:3973
(anonymous) @   useFormAddWorkout.js:184
Promise.catch (async)       
(anonymous) @   useFormAddWorkout.js:182
Promise.then (async)        
onSubmit    @   useFormAddWorkout.js:153
(anonymous) @   bundle.js:40851
(anonymous) @   bundle.js:41169
(anonymous) @   bundle.js:40767
Promise.then (async)        
(anonymous) @   bundle.js:40743
(anonymous) @   bundle.js:41169
(anonymous) @   bundle.js:40831
(anonymous) @   bundle.js:41169
callCallback    @   bundle.js:58478
invokeGuardedCallbackDev    @   bundle.js:58527
invokeGuardedCallback   @   bundle.js:58587
invokeGuardedCallbackAndCatchFirstError @   bundle.js:58602
executeDispatch @   bundle.js:62837
processDispatchQueueItemsInOrder    @   bundle.js:62869
processDispatchQueue    @   bundle.js:62882
dispatchEventsForPlugins    @   bundle.js:62893
(anonymous) @   bundle.js:63104
batchedEventUpdates$1   @   bundle.js:76789
batchedEventUpdates @   bundle.js:58276
dispatchEventForPluginEventSystem   @   bundle.js:63103
attemptToDispatchEvent  @   bundle.js:60586
dispatchEvent   @   bundle.js:60504
unstable_runWithPriority    @   bundle.js:89827
runWithPriority$1   @   bundle.js:65884
discreteUpdates$1   @   bundle.js:76806
discreteUpdates @   bundle.js:58288
dispatchDiscreteEvent

Get route parameters in React

<Route path="chats/:id" element={<Chat />} />
import React from "react";

export default class Chat extends React.Component {
  render() {
    return (
      <>
        {this.props.match.params.id}
      </>
    )
  }
}

If I use this, I only get a white site and the following error:

Chat.js:6 Uncaught TypeError: Cannot read properties of undefined (reading 'params')
    at Chat.render (Chat.js:6:1)
    at finishClassComponent (react-dom.development.js:20487:1)
    at updateClassComponent (react-dom.development.js:20433:1)
    at beginWork (react-dom.development.js:22366:1)
    at HTMLUnknownElement.callCallback (react-dom.development.js:4157:1)
    at Object.invokeGuardedCallbackDev (react-dom.development.js:4206:1)
    at invokeGuardedCallback (react-dom.development.js:4270:1)
    at beginWork$1 (react-dom.development.js:27243:1)
    at performUnitOfWork (react-dom.development.js:26392:1)
    at workLoopSync (react-dom.development.js:26303:1)

How can I get this to work?
No tutorial or googling worked.

(I use react-router-dom v6)

jquery to vanilla js ( I have a code which is about clipboard thing )

I have a code written on jquery.

From https://gist.github.com/nicohaemhouts/0fa3ea89cad0b7d77648

This code is about pasting multiple line into input in html.

 if (window.clipboardData) {
    $('input[type=text]').on('paste', function (e) {
        e.preventDefault();
        $(this).val(window.clipboardData.getData('Text').replace(/(rn|n|r)/gm, " "));
    });
}

clipboardData on first line is not existing in pure js.

Also, I can not understand Fourth line about jquery.

Can you please translate that jquery?

Use PascalCase for React components error when using vue component in React

Using Vuera to use and interact with vue components in React and getting the error message

Use PascalCase for React components, or lowercase for HTML elements.

This occurs when I try to navigate to my vue component.

This is my vue component:

<template>
    <div class="row">

        <div class="col-3">
        </div>
        <div class="col-6">
            <select v-model="language" class="form-select" style="width:50%, margin:auto" aria-label="Default select example" @change="changeLanguageHandler()">
                <option selected>Select your language</option>
                <option value="70">Python</option>
                <option value="63">Javascript</option>
                <option value="52">C++</option>
                <option value="82">SQL</option>
                <option value="81">Scala</option>
            </select>
            <brace style="height: 500px"
                :fontsize="'12px'"
                :theme="'twilight'"
                :mode="this.currentLanguage"
                :codefolding="'markbegin'"
                :softwrap="'free'"
                :selectionstyle="'text'"
                :highlightline="true">
            </brace>
            <button class="btn btn-primary" @click="makeSubmission()"> Run</button>
        </div>
        <div class="col-3">
            <div style="margin-top: 10px">
                <h3>Output</h3>
               <b>{{ this.resp || this.error }}</b>
            </div>
        </div>
     </div>
</template>

<script>
import Brace from 'vue-bulma-brace'
import axios from 'axios'

export default {
  name: 'App',
  components: {
    Brace
  },
    data() {
        return {
            language: 70,
            currentLanguage: 'python',
            baseURL: "https://ce.judge0.com",
            languageMap: {
                70: "python",
                63: "javascript",
                52: "c++",
                82: "sql",
                81: "scala"
            },
            requestBody: {
                    "source_code": "print('testing')",
                    "language_id": "70",
                    "number_of_runs": null,
                    "stdin": "Judge0",
                    "expected_output": null,
                    "cpu_time_limit": null,
                    "cpu_extra_time": null,
                    "wall_time_limit": null,
                    "memory_limit": null,
                    "stack_limit": null,
                    "max_processes_and_or_threads": null,
                    "enable_per_process_and_thread_time_limit": null,
                    "enable_per_process_and_thread_memory_limit": null,
                    "max_file_size": null,
                    "enable_network": null
                },
                token: null,
                resp: null,
                output: null,
                error: null
        }
    },
    methods: {
        threeSecondWait(){
            return new Promise(resolve => setTimeout(() => resolve("result"),3000));
        },

        makeSubmission() {
            console.log('make submission has been triggered')
            console.log('sending:', document.getElementsByClassName('ace_content')[0].innerText)
            this.requestBody.source_code = document.getElementsByClassName('ace_content')[0].innerText
            axios.post(`${this.baseURL}/submissions`, this.requestBody)
                .then((res)=> {
                    console.log('res', res);
                    this.token = res.data.token
                    console.log('token', this.token);
                    this.threeSecondWait().then(()=>{
                        axios.get(`${this.baseURL}/submissions/${this.token}`)
                            .then((res) => {
                            console.log(res.data.stdout)
                            this.resp = res.data.stdout
                            })
                            .catch((err) => {
                            console.log('err', err)
                            })
                    })
                })
                .catch((err)=>{
                    this.error = err.response.data.source_code.toString()
                })
        },
        changeLanguageHandler() {
            this.requestBody.language_id = this.language.toString()
            this.currentLanguage = this.languageMap[this.language]
            console.log('language is', this.currentLanguage)

        }
    }
}
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
  background-color: black;
}
h3 {
    color: white;
    border-bottom:2px solid #CCC;
    padding-bottom:2px;
}
</style>

The React component that will be using this vue component:

import React from 'react'
import App from '../../editor-ui/src/App.vue'

const CodeEditor = () => (
    <div>
        <h1>Testing if this works</h1>
        <App/>
    </div>
)
export default CodeEditor;

my App.js file:

import CodeEditor from './components/code/CodeEditor'
...

const App = () => {

  const childRef = useRef();
  let location = useLocation();

  useEffect(() => {
    const page = location.pathname;
    document.body.classList.add('is-loaded')
    childRef.current.init();
    trackPage(page);
  }, [location]);

  return (
    <ScrollReveal
      ref={childRef}
      children={() => (
        <Switch>
            <AuthProvider>
                <Header/>
                <AppRoute exact path="/" component={Home} layout={LayoutDefault} />
                <AppRoute exact path="/login" component={Login} />
                <AppRoute exact path="/signup" component={Signup} />
                <AppRoute exact path="/code_editor" component={CodeEditor} />
                <PrivateRoute exact path="/profile" component={Profile} render={(props) => <AdminLayout {...props} />} />
            </AuthProvider>
        </Switch>
      )} />
  );
}

export default App;

and in my .babelrc

{
  "presets": ["react-app"],
  "plugins": ["vuera/babel"]
}

This is my first vue app, so pardon the beginner question

Javascript custom markers directions?

I am quite new to this Javascript google maps API Google maps directions simple.
I have tried using the example in my project for the American cities on my project and that works fine. However my project involves trying to get directions to and from custom markers, where I am getting the longitude and latitude from them and displaying the markers on there. What I want to do is get directions to and from these custom markers. Is that even possible.

Whenever I select the places to get directions to and from I get the error, Directions request failed due to

Here is my code:

<div id="floating-panel">
            <select id="start">

            @foreach ($crags as $crag)
                <option value="{{ $crag->id }}">{{ $crag->name_of_crag }}</option>
            @endforeach
        </select>

        <select id="end">
            @foreach ($crags as $crag)
                <option value="{{ $crag->id }}">{{ $crag->name_of_crag }}</option>
            @endforeach

        </select>
    </div>
    <div id="map" style="width: 100%; height: 500px; clear: both"></div>
 <script type="text/javascript">

            var crags = <?php echo json_encode($crags); ?>;

            var map = new google.maps.Map(document.getElementById('map'), {
                zoom: 10,
                center: new google.maps.LatLng(56, -1.56),
                mapTypeId: google.maps.MapTypeId.ROADMAP
            });

            var infowindow = new google.maps.InfoWindow();

            var marker, i;

            var result;
            for (i = 0; i < crags.length; i++) {
                console.log("crag is ",crags[i].type)

                if(crags[i].type=='Granite'){
                marker = new google.maps.Marker({
                    position: new google.maps.LatLng(crags[i].latitude, crags[i].longitude),
                    map: map,
                    icon:'http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|ddd',
                    url: "/crag/" + crags[i].id
                });
                }
                else if(crags[i].type == 'Sandstone'){
                    marker = new google.maps.Marker({
                        position: new google.maps.LatLng(crags[i].latitude, crags[i].longitude),
                        map: map,
                        icon:'http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|0560bd', //blue
                        url: "/crag/" + crags[i].id
                    });
                }
                else{
                    marker = new google.maps.Marker({
                        position: new google.maps.LatLng(crags[i].latitude, crags[i].longitude),
                        map: map,
                        icon:'http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|f31515',//red
                        url: "/crag/" + crags[i].id
                    });
                }


                var link ="http://127.0.0.1:8000" + marker.url;
                var html = "<b>" + crags[i].latitude + "</b> <br/>" + crags[i].longitude + "<br/>" + crags[i].location +
                    "<br/>" + "<a href='" + link + "'>" + "More Details" + "</a>"

                google.maps.event.addListener(marker, 'click', (function (marker, html, infowindow) {
                    return function () {
                        infowindow.setContent(html);
                        infowindow.open(map, marker);

                    }
                })(marker, html, infowindow));
            }
            const directionsService = new google.maps.DirectionsService();
            const directionsRenderer = new google.maps.DirectionsRenderer();


            directionsRenderer.setMap(map);

            const onChangeHandler = function () {
                calculateAndDisplayRoute(directionsService, directionsRenderer);

            };

            document.getElementById("start").addEventListener("change", onChangeHandler);
            document.getElementById("end").addEventListener("change", onChangeHandler);

            function calculateAndDisplayRoute(directionsService, directionsRenderer) {
                directionsService
                    .route({
                        origin: {
                            query: document.getElementById("start").value,
                        },
                        destination: {
                            query: document.getElementById("end").value,
                        },
                        // travelMode: google.maps.TravelMode.DRIVING,
                        travelMode: google.maps.TravelMode.DRIVING,

                    })
                    .then((response) => {
                        directionsRenderer.setDirections(response);
                    })


                        .catch((e) => window.alert("Directions request failed due to " + status));
            }

        </script>

How to map array of object of array of object? Not working in node

I seen many questions including this from 3 hours and still finding solution please help.
Actually I am trying to map in an js file which return an array of object of array of object,

Structure of DataSet : country[{name:value, states: [{name:value},{….},…]}, {……}, ….]

and get an Array of States Name

Please tell me what is wrong in this code Thanks in advance.

const allCountryArray = require('../../data/allCountryArray.js');

const countrySelect = document.querySelector('#country');
const stateSelect = document.querySelector('#state');
const citySelect = document.querySelector('#city');
let countrySelectionValue;
let statesGot;

countrySelect.addEventListener('change', checkCountry);

function checkCountry(e){
    countrySelectionValue = e.target.value;
    if(!countrySelectionValue) return;
    statesGot =  allCountryArray.map(country => {
            if(country.name == countrySelectionValue){
                return country.states.map(state => state.name);
            }
        })
    console.log(statesGot);
}

Change border color of a div conditionally angular

I have these two arrays :

Original Array :

$arr_1=['disappear','rising','filled','decades]; 

User Array:

$arr_2=['disappear','filled','filled','decade]; 

this.indexesAttention=[];
$arr_1.forEach(x=>{   
      //concat two arrays
       this.indexesAttention=[...this.indexesAttention,
                                    ...this.checkValue(x)]
 });

 checkValue(variable:string):number[]
 {
     
    return this.arr_2
    .map((x,index)=>x.trim()==variable.trim()?index:-1)
   .filter(x=>x!=-1) //only want the index>>-1
 }

These should return the matching indexes in this case it should return [0,2] indexes because they are matching but in my case it is returning 0,2,1,3

 [ngStyle]="(indexesAttention.indexOf(i)<0) ? {'border-color':'red','color':'red'} : show_answer === false ? {'border-color': 'black','color':'black'} : {'border-color': 'green','color':'green'}" 

Any solution to resolve this issue, Thanks

React hooks – update state from an input in a child component which is called on a button click

I’m trying to update a state from an input, which works fine when the field is is in the same component, but doesn’t work when I pass it into a child component, seemingly no matter what I pass to it!

const Create = () => {
      const [question, setQuestion] = useState(''); 
      const [components, setComponents] = useState([""]); 

        const handleQInputChange = event => {
              setQuestion(event.target.value)
        }
        
        function addComponent() {
        setComponents([...components, "Question"]) 
}

return (

       <Button onClick={addComponent} text="Next question"/>
            <ol>
                    {components.map((item, i) => ( 
                        <li>
                            <CreateQuestion question={question} onChange= 
                            {handleQInputChange}/>
                        </li> 
                    ))} 
                
            </ol>
)}

and then CreateQuestion component looks like:

     const CreateQuestion = (props) => {

    function handleQInputChange( event ) {
    props.onChange(event.target.value)
    }


    return (
      
        
         <div className="Component">
                <label>Question</label>
                <input
                    name="question"
                    id="question"
                    value={props.value}
                    onChange={props.handleQInputChange}
                    type="text"
                    placeholder="Question"
                />
                <br />

I’ve followed at least 10 guides on how to pass the data back and forth, so it may have become a little convoluted. If I put the Question input directly into the parent component the state updates, so I suspect it’s just me not passing props correctly but completely stuck!

Thank you

How to call a javascript function in ejs

I’ve tried adding an onclick function to my ejs button but it’s not calling the function in my index.js.
here is my ejs button in the views folder

<button onclick="test();">test</button>

here is my index.js

const express = require('express');
const app = express();



const ejs = require('ejs'); //to connect to ejs files
const path = require('path'); //to use redirect and render
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs'); //specify engine



app.get('/', (req, res) => {        
  res.render("index")
})

function test() //here is the function I want called.
  {
    console.log("works")
  }


app.listen(3000)

How do I call a function from ejs? If it is not possible, then how do you change varibles? ex. pg+=1. So the pg in the link increases by 1.

javascript on onclick=”return func();” stop working after first element by id

    <button onclick="return validateEdit();" class="btn btn-primary submit-btn">Submit</button>

function validateEdit() {
  var name = document.getElementById("sftName").value;
  aler("name")
  var startTime = document.getElementById("startTimeEdit").value;
  aler("start time")
}

The function execute first alert and don’t show second aler.I am using also:

$('#edit_shift').on('show.bs.modal', function (event) {
  var anchor = $(event.relatedTarget) // Button that triggered the modal
  var id = anchor.data('whatever')
  var from = anchor.data('fromtime')
  var modal = $(this)
  $("#sftName").attr("value", name);
  $("#startTimeEdit").attr("value", from);

In the another form is working fine

Javascript switch statement does not work

This code works perfectly. But if I uncomment the switch statement, it fails completely. The switch statement seems to be correct. Any help will be greatly appreciated.

<html>
    <body>
         
    
      <canvas id="my-canvas" width="500" height="500"></canvas> 
        
      <script>                      
            
            function draw(n) {
            
                    let canvas = document.querySelector('#my-canvas');
                    let context = canvas.getContext('2d');
                    context.fillStyle = 'black'
                    
                let contourInterval = 1500
                    let contourWidth = 500
                    let fsize = 1000                        
                    let x0 = fsize/2
                    let y0 = fsize/2
              
                for (j=0,y=-y0; j<fsize; j++,y++) {
                    for (i=0,x=-x0; i<fsize; i++,x++) { 
                        /*  
                        switch(n) {
                            case 0:
                                let fun = (x*x + y*y)
                                break;
                            case 1:
                                let fun = (x*x - y*y)                       
                                break;
                            case 2:
                                let fun = 1.0/(x*x + y*y)
                                break;
                            default:
                                let fun = (x*x + y*y)
                            }
                            */
                            let fun = (x*x + y*y)                                   
                            if (Math.abs(fun%contourInterval) < contourWidth) {
                               context.fillRect(x+x0/2,y+y0/2,1,1)
                            }                   
                    }
                    }
            }
                
                draw(1)
         </script>
    </body>      
</html> 

Javascript: dealing with a http promise [duplicate]

I know that there are multiples question on this thread. But I cannot find a mode to solve my question.

I’m writing a simple javascript piece of code to update DNS on Cloudflare.

This is the code:

import * as http from 'http';
import App from "./src/App.js";

const app = new App();

getPublicIp();
const ip = getPublicIp();
console.log(ip);
//update();

function getPublicIp() {
    http.get({'host': 'api.ipify.org', 'port': 80, 'path': '/'}, function(resp) {
        resp.on('data', function(ip) {
            const publicIp = ip.toString();
            return publicIp;
        });
    });
}

function update() {
    app.browseZones()
        .then(zones => app.getZoneId(zones.result, process.env.ZONE))
        .then(zoneId => console.log(zoneId))
        .catch(err => {
            console.log(err)
        });
}

Of course the console.log at line #8 is undefined.

I tried to add also await: const ip = await getPublicIp(); without luck.

How can I get the public ip outside that promise and available at line #8?