How can I pass variables from my post to my get?


programmer man

I am using react/express.

I have a simple web page that takes user input and uses axios.post. In my backend, I need to create a file in my get.

I haven't been able to get the return function to work, I don't want to use a global variable as it has caused errors before.

Is there something I'm missing? How can I access variables getin my request from within my request post.

frontend.js

import React from 'react';
import { useState, useEffect } from "react";
import Calendar from 'react-calendar';
//import 'react-calendar/dist/Calendar.css';
import Axios from 'axios'; 

const CalendarApp = () => {
  var [selectedDate, newDate] = useState(new Date());
  const [event, newEvent] = useState("")
  const [userEvent, setUserEvent] = useState("")
  const [userEventList, setUserEventList] = useState([])
  const [newUserEvent, setNewUserEvent] = useState("")

//Add event to DB
  const addUserEvent = () => {
    var userDate = (selectedDate + "").slice(3, 16);
    console.log("From addUserEvent", userDate)
    if (userEvent === "") {
      //alert("Please enter event")
    }
    else {
      Axios.post("http://localhost:3001/send", {
        userEvent: userEvent, userDate: userDate
      }).then(() => {
        //setUserEventList([...userEventList, { userEvent: userEvent, userDate: userDate}])
      });
      // changes the event list depending on what date the user clicks 
      document.getElementById('ui').value = '';
      setUserEvent(userEvent => userEvent = "")
    }
  };

  const getUserEvent = (userDate) => {
    Axios.get("http://localhost:3001/getData").then((response) => {
      setUserEventList(response.data)
      console.log("response.data: ", response.data)
    });
  };
}

backend.js

//Setting up express, similar to flask
const express = require('express'); 
const app = express() 
const mysql = require('mysql'); 
const cors = require('cors')  

//Setting up SQL, hide password properly 
const db = mysql.createConnection({
    host:'localhost',
    user: 'root',
    password: '******',
    database: 'calendardb',
});

app.use(cors());
app.use(express.json()); 

// insert information in to DB
app.post('/send',(req,res) =>{
    const userEvent = req.body.userEvent
    const userDate = req.body.userDate //<---- Access this variable from the get below
    currentDate = req.body.userDate
    console.log("FROM DB ADD",userDate,"d",currentDate)
    db.query('INSERT INTO calevent (userEvent, userDate) VALUES (?,?)', 
    [userEvent,userDate], (err,result) =>{
        if(err){
            console.log(err)
        } else{
            res.send("Data send to DB")
        }
    }
    );
  });

//Getting Specific  data from DB
app.get("/getData",(req, res) =>{
    db.query("SELECT * FROM calevent WHERE userDate = ?", [userDate], (err, result) => {
        if(err){
            console.log(err)
        }else{
            res.send(result)
        }
        console.log(result)
    });
});
Japan

REST calls are stateless, which means that each request must be independent of state. If your goal is a RESTful service, I recommend against this. Although, saving it in a session ( express-session ) or something like that would work, I would recommend adding that along with the param userDatein the get call (since GET requests won't have a body). You've userDatesent the getUserEventfunction an unused parameter , similar to this.

Axios.get("http://localhost:3001/getData", { params: { userDate }} )

Related


How can I pass variables from my view to my controller?

Luke Dangerous Kozorowski I have generated a dropdown <select>on my view page with data from a stored procedure. Using JavaScript, I accessed the selection <option>and saved the text into a variable. Now I need to send that variable back to my controller so I

How can I pass php variables from my select to jquery?

Liliymas I have next code to load all countries on my website: $(document).ready(function() { $.ajax({ type: 'GET', url: '/comunidades', success: function(response) { $("#cbx_comunidad").empty(); // console.log(response); $("#c

How can I pass php variables from my select to jquery?

Liliymas I have next code to load all countries on my website: $(document).ready(function() { $.ajax({ type: 'GET', url: '/comunidades', success: function(response) { $("#cbx_comunidad").empty(); // console.log(response); $("#c

How can I pass variables from options to my controller?

Sam Bush Can someone tell me how to collect the values? Please select on.change in the drop down box and use the value as a variable in the controller. For some reason the $ColorPicked variable won't be in $scope.base=response.data.type. $ColorPicked is rotate

How can I pass php variables from my select to jquery?

Liliymas I have next code to load all countries on my website: $(document).ready(function() { $.ajax({ type: 'GET', url: '/comunidades', success: function(response) { $("#cbx_comunidad").empty(); // console.log(response); $("#c

How can I pass python variables to my template via flask?

Eric Nagy I made a web app with flask. I want to pass a variable value to my template to set a property. In python: web_size="100%" @app.route('/') def home(): return render_template("web.html") def size(): return "50px" In the html5 file I used this: w

How can I pass python variables to my template via flask?

Eric Nagy I made a web app with flask. I want to pass a variable value to my template to set a property. In python: web_size="100%" @app.route('/') def home(): return render_template("web.html") def size(): return "50px" In the html5 file I used this: w

How can I pass the created post to my own view in Flask?

big boy 1337 Here is the code. I have a model which has a class Item. class Item(db.Model): id = db.Column(db.Integer,primary_key=True) title = db.Column(db.String(80),unique=True) content = db.Column(db.String(80),unique=True) category = db.Co

How can I get my ID from the button to my controller?

Buzken What am I doing wrong? I want to add an order to an existing customer, but the customer's id doesn't match the controller. public ActionResult AddOrder(Guid? customerId) { if (customerId == null) { throw new ArgumentNullException(nameof(

How can I get my ID from the button to my controller?

Buzken What am I doing wrong? I want to add an order to an existing customer, but the customer's id doesn't match the controller. public ActionResult AddOrder(Guid? customerId) { if (customerId == null) { throw new ArgumentNullException(nameof(

How can I get the hashed password to pass to my database?

Howie I can run the tests in Postman, but for some reason I can't pass the hashed password into the database correctly. const express = require("express"); // const helmet = require("helmet"); const { User } = require("./db/models"); const bcrypt = require("bc

How can I get the hashed password to pass to my database?

Howie I can run the tests in Postman, but for some reason I can't pass the hashed password into the database correctly. const express = require("express"); // const helmet = require("helmet"); const { User } = require("./db/models"); const bcrypt = require("bc

How can I get the hashed password to pass to my database?

Howie I can run the tests in Postman, but for some reason I can't pass the hashed password into the database correctly. const express = require("express"); // const helmet = require("helmet"); const { User } = require("./db/models"); const bcrypt = require("bc

How can I get the hashed password to pass to my database?

Howie I can run the tests in Postman, but for some reason I can't pass the hashed password into the database correctly. const express = require("express"); // const helmet = require("helmet"); const { User } = require("./db/models"); const bcrypt = require("bc

How can I get the hashed password to pass to my database?

Howie I can run the tests in Postman, but for some reason I can't pass the hashed password into the database correctly. const express = require("express"); // const helmet = require("helmet"); const { User } = require("./db/models"); const bcrypt = require("bc

How can I get R to read my environment variables?

Jordan Bell I'm running R on an EC2 spot instance and need R to terminate the instance and cancel the spot request after the script runs. For this I have set the "request id" in an environment variable /.bashrcand my plan is to simply call the following code i

How can I get R to read my environment variables?

Jordan Bell I'm running R on an EC2 spot instance and need R to terminate the instance and cancel the spot request after the script runs. For this I have set the "request id" in an environment variable /.bashrcand my plan is to simply call the following code i