Guide on making a POST request through axios for REST API:

How can I send a POST request using axios to a REST API?

Headers

I'm experiencing issues with incorrect headers when making GET requests, and I'm not sure why. Additionally, I've found that the documentation for axios doesn't always work properly.

Here's an example of a successful GET request: Dynamic host in axios

const configAxios = {
  headers: {
    'Content-Type': 'application/json; charset=UTF-8',
    'Access-Control-Allow-Origin': '*',
  },
};
const data = JSON.stringify({
  cardData: this.cardData.brand,
});
axios.post('api/products', {
  data,
},
  configAxios,
)
.then((req) => {
  this.data = req.data;
  console.log(req);
})
.catch((err) => {
  console.warn('error during http call', err);
});

To access the API host, you need to do the following:

p.s.: This method is necessary for it to work correctly.

const baseURL = 'http://localhost:8080';
if (typeof baseURL !== 'undefined') {
  Vue.axios.defaults.baseURL = baseURL;
}

  • Axios version: e.g.: v0.16.2
  • Environment: e.g.: node v8.9.4, chrome 64.0.3282.119, Ubuntu 16.04
  • Symfony 4.0.4
  • Vue.js 2.4.2
  • vue-axios 2.0.2

Answer №1

When the API and client reside on different domain names, it is crucial to set up CORS headers correctly to allow communication between the two. It is also important to whitelist authorized headers for security reasons.

To accomplish this in API Platform and Symfony, consider using the helpful NelmioCorsBundle. For those using Symfony 4/Flex, simply execute:

$ composer req cors

Upon execution, the package will be automatically installed and configured properly. Even the `Content-Type` header will be appropriately whitelisted.

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

Step-by-step guide to creating a pop-up div that appears on hover and remains visible when clicked

I'm trying to figure out how to make a popup appear when the mouse hovers over it and then stay visible when clicked on. The issue I'm facing is that currently, the popup disappears when the mouse moves away from it. How can I modify the code so ...

Verify if the form has been refreshed in React JS

In my React application, I have a form inside a modal pop-up. When the user closes the pop-up, I want to check for any changes made in the form fields. If there are changes, I will display a confirmation modal; if not, I will simply close the pop-up. <F ...

The AJAX request and UPDATE query are not working as expected

Currently, I am attempting to use an UPDATE query with an AJAX call to update a player's division by sending it to the update_divisions.php file. The process involves selecting a user from one select box and choosing the desired division from another ...

When the child content surpasses the height of the parent, you can scroll within an overflow:visible; div

My sidebar navigation menu includes children and sub-children that are revealed on hover. You can view a simplified version of it in this jsfiddle link: https://jsfiddle.net/s096zfpd/ Although the example provided is basic, my main concern arises when the ...

Tips for passing data to a child component from a computed property

Currently in the process of setting up a filter using vue-multiselect. Everything seems to be working fine, but there's one issue I can't seem to resolve. Upon page reload, the label (v-model) appears empty. The root cause seems to be that the v ...

What is causing the issue with mongoose populate not working when trying to populate an array?

My database setup includes 2 schemas: const mongoose = require('mongoose'); const PinSchema = new mongoose.Schema({ title: String, content: String, image: String, latitude: Number, longitude: Number, author: { type: mongoose.Sch ...

The CORS policy is preventing access: The requested resource does not have the necessary 'Access-Control-Allow-Origin' header. Transitioning from Vue to Spring

Having trouble with axios in Vue connecting to Spring Check the vue component script View an image related to this issue here Also review your vue.config.js file Make sure your Spring controller is set up correctly If you're getting an error code ...

Detecting modifications to an array with MobX

Today marks my first foray into learning MobX and I am eager to discover how to track all array changes (insertions, deletions, etc) with MobX. A practical example would definitely help clarify this: const TodoList = ({todos}) => ( <ul> ...

When using React, I noticed that adding a new product causes its attributes to change after adding another product with different attributes on the same page

Imagine you are browsing the product page for a Nike T-shirt. You select black color and size S, adding it to your cart. The cart now shows 1 Nike T-SHIRT with attributes color: black, size: S. However, if you then switch to white color and size M on the ...

How can I display and utilize the selected value from a Rails select form before submitting it?

Currently, I am in the process of developing a multi-step form for placing orders. This form includes two dropdown selectors - one for shipping countries and another for shipping services. Once a country is selected, all available shipping services for tha ...

Enhancing Angular with Plotly: Implementing click events on bar chart legends

I'm currently working on implementing color pickers for my plotly-plot charts within an Angular template. I am looking to add a function that triggers when the chart legend is clicked. How can I achieve this and get a click event for the chart legends ...

issue encountered when attempting to use string.replace with regex

When using a regex like this: I am attempting to replace "subdir" with a custom string using the string.replace method. However, when I use myStr.replace(/^.*\/\/.*\.net\/.*\/(.*)\/.*\z/, otherStr) The result is not as ...

I'm attempting to make this script function correctly when an image is loaded

Can anyone help me figure out how to make this script function on image load instead of onclick? I came across the script on stackoverflow, but it was originally set up for onclick. I want it to work for onload or .load HTML====== <div id="contai ...

The powerful combination of Nuxt, Vuex, and Computed Properties allows for

Currently exploring Nuxt.js with Vuex, I have created a basic form containing an email field, a password field, and a button. All my state, mutations, and actions are functioning correctly. However, I encountered an issue when trying to create a computed ...

Display a single submenu on mouseover using Javascript

Hello there, I have been working on creating a small menu using only Javascript, but I am facing an issue where the onmouseover event is displaying all submenus instead of just one. Below is the section of code that is supposed to change style.display to ...

"Enhance Your Website with jQuery Mobile's Multi-Page Setup and Panel

I am currently facing the challenge of managing multiple pages within a single document and I would like to utilize jQM 1.3's Panel widget to control navigation between these pages. However, the issue arises from the requirement that Panels must be co ...

Searching for the Magic Index using Binary Search

Currently working on mastering binary search and encountering difficulties while trying to use it to locate the "magic index" within an array, where the magic index is defined as A[i] == i. While I have come across some Java implementations using recursio ...

Vue.js encountered an error while trying to load the component: either the template or render function is not

Currently I am delving into the realm of Vue.js paired with Laravel by following this series, where the narrator seems to breeze through without encountering any errors. Unfortunately, when I attempted to change the route, a pesky error made an appearance. ...

Can you explain the purpose of this script? Is it considered harmful?

Today, I received a suspicious phishing email containing the following JavaScript code: <script type="text/javascript" language="Javascript1.1"> <!-- Begin var bCancel = false; function validateRegistrationDetails(form) { hm ...

What is the best way to verify a v-if condition with an array in Vue.js HTML?

I am looking to dynamically add rows based on multiple options selected from a dropdown menu. When I select one option at a time, I am able to get the desired result. However, when I select multiple options, no rows are added. For example, if I select opt ...