Struggling with retrieving empty parameters, queries, and body from an Axios API call for the past three days. It's a learning experience as I am new to the MERN stack

There seems to be an issue where only empty JSON like {} is coming as output.

I am looking for a way to access the parameters sent from the routes in this scenario.

On the Frontend:

let api = axios.create({
  baseURL: "http://localhost:5000/validateSignIn",
})

let config = {
    headers: {
       'Content-Type': 'application/x-www-form-urlencoded',
    } 
}

export default function TopBar(input){

    function postCredentials(un, pw){
        let params = new URLSearchParams();
        params.append('username', un);
        params.append('password', pw);
        let getResponse =  api.get('/', params, config)
        .then(response=>{
          return (response.data)
        }).catch()
        return getResponse
      }

    async function validateSignIn(){
        let user = document.getElementById("username").value
        let success = await(postCredentials(user, document.getElementById("password").value))
        console.log(success)
        if(success){
            input.setState({"name":user})
            return input.setSignedIn(true);
        }
        else{
            console.log("invalid login attempt")
        }
    }
    return(
        <div className="signInPage">
            <div>Enter UserName: </div>
            <input type="username" id="username" maxLength="32" autoComplete="off">                
            </input>
            <div>Enter Password: </div>
            <input type="password" id="password" maxLength="32" autoComplete="off">                
            </input>
            <br />
            <button onClick={() => validateSignIn()}>Click to sign in</button>
        </div>
    )
}

Server Side Setup:

const app = express();

app.use(express.json())
app.use(express.urlencoded({ extended: true }))
app.use(cors())

app.all("/", function(req, res, next) {
    req.header("Origin", "http://localhost:3000/");
    return next();
});

app.use('/login', loginRoutes)
app.use('/validateSignIn', SignInRoutes)

const PORT = process.env.PORT || 5000

Routing Configuration:

const router = express.Router();

export const getSignin = (req, res) => { 
    console.log("params:" + JSON.stringify(req.params))
    console.log("query:" + JSON.stringify(req.query))
    console.log("body:" + JSON.stringify(req.body))

    if(!req.username)
        res.send(false)
    else{res.send(true)}
}

Current Output:

{
params:{}
query:{}
body:{}
}

Note: The goal is to have the username and password sent from the frontend accessible somewhere on the server side. This information can be stored in body, query, params, or any other reachable location.

Answer №1

It appears that the solution is that sending information in the body is not possible with a GET request, but it does work with a POST request. This discovery was made after consulting the API documentation located here: https://www.npmjs.com/package/axios#axios-api

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way to use Apache to consistently direct all incoming calls from one port to a specific URL on a different port?

I am currently running a sails.js application on the default port 1337, with an apache proxy set up on port 8080: [root@ip-192-168-0-XX conf.d]# cat nodetest.conf Listen 8080 <VirtualHost 192.168.0.XX:8080> Options -Indexes ProxyRequests on ...

I encountered a syntax error while implementing the filter method in ReactJS

I am encountering a syntax issue while using the filter method in an API to retrieve a value. The error I'm getting is "Parsing error: Unexpected token, expected ','." I can't seem to figure out what's causing this problem. Can any ...

Tips for updating multiple fields in Prisma ORM

Is there a way to upsert multiple fields in Prisma ORM using just one query? I'm looking for a solution that allows me to upsert all fields at once, without having to do it individually. Is this possible? ...

Unlocking the Power of Deployd: A Comprehensive Guide to Harnessing dpd-passport for Safe

Firstly, I must express my appreciation for Deployd. I am eager to utilize it in a production environment; however, I require OAuth and social logins integration. To achieve this, I have installed the dpd-passport module. Although it functions admirably, I ...

`It is important to note that in Tailwind CSS, `h-8` does not supersede `h-4

I developed an Icon component that looks like this: import { IconProp, library } from "@fortawesome/fontawesome-svg-core"; import { far } from "@fortawesome/free-regular-svg-icons"; import { fas } from "@fortawesome/free-solid-svg- ...

Upon integrating redux-persist, the React app's interface disappears, leaving a blank screen

I am currently developing a social media MERN website and integrating redux-persist to locally store the updated state. Below are three code snippets from different files: Here is my implementation of redux-persist: import { configureStore } from "@r ...

Error: Class cannot be loaded by React Webpack loader

I'm encountering an issue with my two typescript packages - a React application and an infrastructure package. The React app has a dependency on the infrastructure package (currently linked via npm). After adding a new class to the infrastructure pack ...

What strategies and techniques should be considered when creating websites optimized for mobile devices?

With a wealth of experience in programming languages like Java, Python, and C, I actively engage in self-study to enhance my skills. While I have dabbled in creating mobile-friendly websites, upon reviewing my work, it is evident that my frontend developme ...

How can we ensure the discord client object is easily accessible within event files?

I'm a beginner with Discord.js and I've been trying to figure out how to allow event and command files to access the main client instance. I want to be able to call client.database in an event file for CRUD operations, but I'm confused on ho ...

What is the best method to calculate the total of multiple input values from various cells and display it in the final cell of an Angular table?

Hey there! I have a challenge where I need to calculate the sum of input values for each cell and display it dynamically in the last cell of the row. Take a look at the image below: https://i.stack.imgur.com/0iKEE.png In the image, you can see that the nu ...

Using electron cookies in Angular involves integrating Electron's native cookie functionality into an

I am currently dealing with electron and looking to implement cookies conditionally in my project. If the application is built using electron, I want to utilize Electron Cookies; otherwise, I plan to use Angular Cookies. However, I'm encountering diff ...

Uploading Files to Amazon S3 Using Client-Side Technology

Seeking guidance on how to enable users of my NodeJS/Express webapp, hosted on AWS Elastic Beanstalk, to upload profile pictures directly to AWS S3. I prefer direct uploading to S3 as I intend to support larger file uploads in the future. Though inexperi ...

Is it possible to retrieve the createdAt timestamp without displaying the 'GMT+0000 (Coordinated Universal Time)'?

After conducting an extensive search, I have yet to find a satisfactory answer. My goal is to configure it without including the CUT time. {name: "Registered:", value: `${user.createdAt}`}, {name: "Joined:", value: `${message.guild.joinedAt}`} Presently, ...

I'm attempting to render HTML emails in ReactJS

I have been attempting to display an HTML page in React JS, but I am not achieving the same appearance. Here is the code snippet I used in React JS: <div dangerouslySetInnerHTML={{ __html: data }}/> When executed in regular HTML, the page looks lik ...

Are JSON Web Tokens (JWT) too lengthy to transmit via client URL? Exploring Node.js and Express for authentication purposes

I need to authenticate a user's email address using JWT instead of OAuth. This is necessary because users will be signing up with their work email and need to verify it. To do this, I have added an "isVerified" field to my User model. When a user sign ...

The Material UI Select Component has the ability to transform a controlled text input into an uncontrolled one

I encountered a warning in the console while trying to update the value of a Select input. The warning message is as follows: index.js:1446 Warning: A component is changing a controlled input of type text to be uncontrolled. Input elements should not swi ...

Initiating Next.js

What is the optimal location to initialize my Next JS application? I am currently doing this at the beginning of my _app.tsx component. Will these be configured before getInitialProps runs on the server? // pages/_app.js import axios from 'axios&apos ...

Styles are ineffective on the focus property, although they do work before the focus is applied

I'm having trouble changing the font color of the TextInput in material UI. It seems to change to white when I click away, but then reverts back to a purple-ish color (the default) when I focus on it again. I'm not sure what I'm missing here ...

Nextjs version 13 encountered hydration failure due to discrepancies between the initial UI and the server-rendered content

I am currently utilizing the latest version 13.1.0. I have implemented a ContextProvider that allows switching between light and dark themes. 'use client'; import { Theme, ThemeContext } from '@store/theme'; import { ReactNode, useState ...

Establishing a webhook for a node.js application using AWS

After successfully setting up a node.js app and deploying it onto elastic beanstalk, I am now looking to establish a webhook for the app to listen to a typeform survey. What would be the most efficient method for achieving this? Should I opt for lambda i ...