Acquiring POST parameters within Laravel's Controller from JavaScript or Vue transmission

I am trying to send Form data from a Vue component to a Laravel API using the POST method.

Although Laravel is returning a successful response, I am encountering difficulty in handling the POST data within the Laravel controller.

Below is the code for the client side:

 let body = JSON.stringify({
      'email': user.email,
      'password': user.password,
  });

  fetch("/login", {
         method: "POST",
         headers: new Headers({
            'Content-Type': 'application/x-www-form-urlencoded',
            'X-CSRF-TOKEN': user.token,
             body: body
                })
   })

This is the controller:

namespace App\Http\Controllers\Auth;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class LoginJWTController extends Controller{
  public function login(Request $request){
    print_r ($request->all());
  }
}

However, the response (200 OK) returns an empty array: array[]

Upon inspecting the request header, I notice the following:

body: {"email":"example@email.com","password":"12345678"}

Why am I not receiving any POST data in my Controller? What could be missing?

Thank you for your assistance!

Answer №1

Your headers currently include the body, which is incorrect.

Here's a suggested fix:

let requestBody = JSON.stringify({
    'username': user.username,
    'password': user.password,
});
fetch("/authenticate", {
     method: "POST",
     headers: new Headers({
        'Content-Type': 'application/json',
        'X-CUSTOM-TOKEN': user.token, // NOTE: not X_CUSTOM_TOKEN
     }),
     body: requestBody
})

Make sure to set the content type to application/json as indicated by Salman Zafar in the comments.

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

Looking for some guidance on grasping the concept of strict mode in React and determining what actions can be considered side effects

The other day, I came across a strange bug in React and here is a simplified version of it. let count = 0; export default function App() { const [countState, setCountState] = useState(count); const [countState2, setCountState2] = useState(count); con ...

The chosen options will automatically populate the text-boxes that require dynamic summation

I am encountering an issue with a select option that should dynamically populate specific values in text-boxes (different prices) based on the selected option. The goal is to sum up the values in the text-boxes and display the total in another text-box. Ho ...

Project in Three.js where the camera remains focused on the object while in a top-down perspective

I am currently working on developing a top-down game using Three.js, inspired by classic arcade games like Frogger. I am facing challenges in ensuring that the camera stays centered on the main character as it moves across the screen. I am currently util ...

Effect of Ajax calls on pagination in Laravel Views

I have a Laravel project in userlist.blade.php where I display the list of users. Everything is working fine, but I have used a select field to limit the pagination by different values. With the help of Nitish Kumar on Stack Overflow, I was able to retriev ...

Tick the checkboxes that are not disabled, and leave the disabled ones unchecked

Currently, I am employing Jquery for the purpose of checking and unchecking checkboxes. However, some of these boxes are disabled, thus there is no need for them to be checked. Is there a method by which I can instruct the script to disregard disabled che ...

What is the best way to arrange the elements of a dropdown list in reverse order?

I have the following code snippet used to retrieve data from a database and display it in a dropdown list: @{ int m = 1; foreach (var item in Model.MessagesList) { if (@item.receiverUserId == userId) { <li> <a class=&qu ...

Using an onclick function to increment and decrement values

Can anyone help me figure out how to reverse a function onclick? Here is the function: var theTotal = 0; $('button').click(function(){ theTotal = Number(theTotal) + Number($(this).val()); $('.total').text(theTotal); }); ...

Analyzing the value of a tab with Protractor测试

Below is my HTML code showcasing a list of tabs: <mat-tab-group> <mat-tab label="A"> <app-A></app-A> </mat-tab> <mat-tab label="B"> <app-B></app-B> </mat ...

Error: Unable to locate the include file

Hello, I am currently a student working on a project where I am attempting to retrieve a list of books from the server and display them one by one using ejs. Here is an overview of my project structure: | |-----routes | |-----index.js |-----vie ...

Ways to update a PHP array

I have a simple inquiry without an answer yet. Is there a way to transform my array from this: [{"sku":"6"},{"buyers":"7"},{"base":"8"}] to this: [{"sku":"6","buyers":"7","base":"8"}] I am dealing with three queries for three separate database tables: ...

Incorporating Keyboard Features into Buttons

How can I toggle the page selectors in #pageList using a keyboard shortcut instead of clicking on the .togglePL button? I've tried looking up solutions online and asking questions here, but haven't found a working solution yet. Below is the code ...

Update the website's navigation key for improved user experience

Can the navigation key on a website be altered from 'Tab' to another key, such as 'Enter', allowing for the focus to shift to the next element with the corresponding 'tabindex' when the 'Enter' key is pressed? ...

What is the hierarchy for displaying elements depending on the props?

I have developed a search input component that includes an icon which I want to reposition (either on the left or right side) depending on different scenarios. This input is part of a bootstrap input-group, so modifying the order of elements within my di ...

What is the reason for parent rows not stretching fully across the width of the page?

I am working on creating a simple table in Vue.js with Bootstrap. When the arrow is clicked, the child row is displayed, and I want it to appear below the parent row. I achieved this by setting display:flexbox; flex-direction:column; Here is the HTML tabl ...

Exploring VueJs 3's Composition API with Jest: Testing the emission of input component events

I need help testing the event emitting functionality of a VueJs 3 input component. Below is my current code: TextInput <template> <input v-model="input" /> </template> <script> import { watch } from '@vue/composition-api&ap ...

Differentiating between mouseenter and tap events: What's the key?

When a mouseenter event is present, touch-enabled devices will activate this event when the user taps on the element. Is there a way to differentiate between an actual physical mouse entering and a simulated tap (which resembles a mouse enter)? ...

Guide on setting up a Redirect URL with React Router

I am aiming to trigger a redirect URL event using ReactJS. Is there a way to achieve this? I have already attempted the following: successRedirect(){ this.transitionTo('/'); } as well as successRedirect(){ this.router.transitionTo ...

Unable to manage the DatePicker error in Material UI

I am facing an issue with the DatePicker component where it displays a red border when there is an empty value. Setting true/false to error attribute does not seem to have any effect. Even passing error to the TextField component does not change anything. ...

Guide on how to submit an image along with text using AJAX, PHP, and HTML

Hey there! I'm currently working on a project where I need to upload an image with comments added into a database using a combination of PHP, AJAX, and HTML. Let me show you the HTML part first: <form name="form1" enctype="multipart/form-data" ac ...

Is it possible to retrieve the index of a particular element within an array during an update operation in MongoDB?

After executing the following update statement const result = await Post.updateOne({_id: postId},{ $pull: {reacts: {publisher: req.query.publisher}}, $inc: {postPoints: - reactsEnum[ReactType]} }); I am interested in obtaining the ...