Encountering a 500 error while attempting to send data to an API route within a Laravel web page using XMLHttpRequest at http://127:8000/api/v1/exemp. Can anyone

let requestData = {
  products: [
    {
      description: "product1",
      barcode: "123456",
      price: 10,
      note: "note1"
    },
    {
      description: "product2",
      barcode: "654321",
      price: 20,
      note: "note2"
    }
  ]
};

let xhr = new XMLHttpRequest();
xhr.open("POST", "http://localhost:8000/api/v1/cotacao", true);
xhr.setRequestHeader("Content-Type", "application/json");
let csrfToken = document.querySelector('meta[name="csrf-token"]').getAttribute("content");
xhr.setRequestHeader("X-CSRF-TOKEN", csrfToken);

xhr.onreadystatechange = function() {
  if (xhr.readyState === 4 && xhr.status === 200) {
    console.log(xhr.responseText);
  }
};
xhr.send(JSON.stringify(requestData));

xhr.setRequestHeader("X-CSRF-TOKEN", document.querySelector('meta[name="csrf-token"]')?.getAttribute("content")); return document.querySelector('meta[name="csrf-token"]').getAttribute("content") = Uncaught TypeError: Cannot read properties of null (reading 'getAttribute') at :1:51

Answer №1

[resolution] insert 'Cors' => \App\Http\Middleware\Cors::class into the code.

Cors::class{
return $next($request)
             ->header('Access-Control-Allow-Origin', '*')
             ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')
             ->header('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type, X-Token-Auth, Authorization');
}

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

Tips for executing several ajax requests at the same time

I am facing an issue with my AJAX requests in Laravel. When I fire off the first AJAX request, it should trigger the second one immediately afterwards. Unfortunately, the second AJAX call is not happening until the first one completes. Is there a way to ma ...

Start a timer in CodeIgniter when a button is clicked and show the time elapsed

Just a heads up: I am currently in the learning process. While I have some experience with PHP, my knowledge of Java is very limited or non-existent. In the past, I've received negative feedback due to this lack of experience. So, here I am giving it ...

AngularJS filter date is returning a value of NaN-NaN-NaN

I'm facing an issue where the filter I developed is functioning properly on Chrome but not on Firefox. I am puzzled as to why this might be happening. myApp.filter('dateCustom', [ '$filter', function ($filter) { return funct ...

Prevent my application from being idle (Cordova/Android)

I have recently developed an Android app using a node.js webpack project. After installing the app on my phone, I observed that it enters a sleep mode along with the phone. Consequently, a JavaScript timer I set up stops functioning as intended: pingTime ...

Changing the color of a progress bar in Bootstrap based on a specific percentage level

var elem = document.getElementById("progress-bar"); var progress = 75; elem.style.width = 80 + '%'; if (progress > 80) { elem.style.background = "red"; } #myProgress { height: 5px; } #progress-bar { w ...

Having trouble with UseSelector in React Redux?

I am currently working on a exercise to better understand the react-redux process, but I seem to have hit a roadblock. Any assistance would be greatly appreciated. One interesting observation is that when I subscribe and log the store into the console, it ...

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? ...

The system cannot locate the "default" task. Please consider using the --force option to proceed. The process has been halted due to warnings

Below is the content of my gruntfile.js file var fs = require("fs"), browserify = require("browserify"), pkg = require("./package.json"); module.exports = function(grunt) { grunt.initConfig({ mochaTest: { test: { options: { ...

Customizing the appearance of React Navigation StackNavigator through background color changes and styling

Recently delving into React Native, I've managed to create a basic app with three different scenes. Initially, I used Navigator for navigation purposes, but found it to be sluggish and decided to give React Navigation (found at https://reactnavigation ...

The MySQL query is returning a blank result with only the column headings displaying

I have been working on improving my skills in PHP and AJAX by developing an application that enables users to search a database for real-time product stock information. Currently, I am facing an issue where the headings are displayed when a user types a le ...

Challenges in achieving seamless interaction between Javascript Form and Ajax for logging in to a Secure Magento Store

My Webdeveloper abandoned me and my form doesn't seem to work always. When clicked it doesn't appear to do anything (just shows the "javascript:;" href on the browser status bar), but sometimes it works... I've searched everywhere for a so ...

Using PHP and AJAX to implement pagination feature from a file

Looking to implement pagination in PHP using AJAX, where data is fetched from a file. When searching for a keyword, the page displays the first 20 records from the file. Now, I want to show the remaining records from the file with pagination. Any suggest ...

Troubleshooting challenges with updating Ajax (SQL and add-ons)

I am currently facing some specific issues with an ajax update feature, but I am confident that it just requires some fine-tuning to work perfectly. Below, I will outline the problems clearly: In my setup, there are two files that interact with each othe ...

Select preselected options in a multi-select dropdown using Knockout.js

I have a select multi that I've bound to a model, and now I want to select some values that were previously selected using a second model. It seems like a simple task, but in Knockout.js it's proving to be more complicated than expected. Here is ...

Tips for retrieving values from numerous checkboxes sharing the same class using jQuery

Currently, I am struggling with getting the values of all checkboxes that are checked using jquery. My goal is to store these values in an array, but I am encountering difficulties. Can anyone provide me with guidance on how to achieve this? Below is what ...

Having trouble grasping the problem with the connection

While I have worked with this type of binding (using knockout.js) in the past without any issues, a new problem has come up today. Specifically: I have a complex view model that consists of "parts" based on a certain process parameter. Although the entire ...

Configuring settings for gulp-jshint

I'm currently utilizing gulp to compile my JavaScript code. My intention is to run jshint on the files before concatenating them, but I'm encountering difficulties in configuring the options properly. Am I handling this process correctly? var re ...

Unlock TypeScript code suggestions for extended objects

In my app, I use a configuration file named conf.ts to consolidate config values from other files for better organization. By merging these values, it becomes more convenient to access them using Conf.MY_LONG_NAMED_VALUE rather than Conf.SubCategory.MY_LON ...

Clicking on the delete option will remove the corresponding row of Firebase data

I am encountering an issue that appears to be easy but causing trouble. My goal is to delete a specific row in an HTML table containing data from Firebase. I have managed to delete the entire parent node of users in Firebase when clicking on "Delete" withi ...

Toggle between classes by clicking on the next or back button

Looking to create a multi-step form where the initial step is visible while the rest are hidden using the "hide" class. I want to toggle visibility of each step with Next and Back buttons, displaying only one step at a time. Can someone assist with this? ...