HTTP Requests in Velo

Expand your website’s capabilities by using "wix-fetch" to make various HTTP requests.

Different HTTP Requests

Previously, we covered how getJSON() can be used to “ask” for information from another website through a GET request. The GET request works by calling a URL endpoint, which is the specified location from where we can retrieve resources. When we call the getJSON() function, Wix handles the GET request behind the scenes based on the URL we provide, allowing us to easily retrieve data from the server.

Types of HTTP Requests

Our websites could be boring if we’re only able to GET information and not manipulate it in any other way. Fortunately, there are other HTTP request verbs that perform various actions for our websites:

  • GET: retrieve a specific resource by ID or a collection of resources.
  • DELETE: remove a specific resource by ID.
  • PUT: update a specific resource by ID.
  • POST: create a new resource.

In this article, we will focus on using a POST request to allow for even more user interaction on your Wix websites!

Making a POST Request

POST requests are important because they allow the browser to send data to the server and create a new resource. With POST requests, we can expand the capabilities of our websites to access other sites and gain a wealth of additional functionality.

In fact, you have likely used POST requests many times before — including today! For example, when you log in to the Codecademy website, you are sending your username and password to the server using a POST request. The server will then check whether your login credentials are valid and send back a response that will allow or deny access to your personal Codecademy dashboard.

Syntax of the POST Request

To implement a POST request, we must again use the fetch() function of the wix-fetch module, which often occurs on the backend.

import { fetch } from 'wix-fetch';
fetch('https://someapi.com/api/endpoint', {
'method': 'post',
'headers': {
'Content-Type': 'application/x-www-form-urlencoded'
},
'body': 'somekey=somevalue'
})

As seen in the boilerplate code above, the fetch() function is used to contact a mocked-up URL with a POST request. The second argument of the fetch() function is the WixFetchRequest object, which contains information about the HTTP request. This object can be used to pass in content that needs to be sent to the server, such as the following properties:

  • method which is a string representing the specific HTTP request method to use. To make a POST request, we must designate this property as 'post'.
  • headers is an object that is used to pass along information about the request body to the server (in this case, the Content-Type of the body).
  • body is a string representing the request data we’re sending, also known as the payload. In more complex programs, the body of a POST request is where the user will send information to the server, such as login credentials.

Handling the Response

We’ve used the fetch() function and its WixFetchRequest argument to send the endpoint our data. Afterward, we need to handle the data and the response that comes back from the endpoint.

import { fetch } from 'wix-fetch';
fetch('https://someapi.com/api/endpoint', {
'method': 'post',
'headers': {
'Content-Type': 'application/x-www-form-urlencoded'
},
'body': 'somekey=somevalue'
})
.then((httpResponse) => {
if (httpResponse.ok) {
return httpResponse.json();
} else {
return Promise.reject('Fetch did not succeed');
}
})
.then((json) => console.log(json.importantData))
.catch((err) => console.log(err));

Since fetch() returns a WixFetchResponse object which is a Promise, we also have to chain the appropriate .then() and .catch() methods.

Through the .then() method, we can first check if the HTTP request was successful by using httpResponse.ok to get the returned HTTP status code. If successful, we can then get the JSON data that is returned from httpResponse.json() as another Promise (in more complex programs, this can be data like authentication tokens to allow for the user to login). If we fail to receive the proper WixFetchResponse, the .catch() method is executed, which prints out the error in this case.

Putting It Together

Let’s take a look at how we can use POST requests to calculate mathematical expressions for a Wix calculator widget.

To prevent issues with CORS and avoid any security concerns, we often have to implement fetch() on the backend. We’ll create a backend file called calculator.jsw with the following code:

import { fetch } from 'wix-fetch';
export function calculate (expression) {
return fetch('http://api.mathjs.org/v4/', {
'method': 'post',
'headers': {
'Content-Type': 'application/json'
},
'body': JSON.stringify({ expr: expression })
})
.then((httpResponse) => {
if (httpResponse.ok) {
return httpResponse.json();
} else {
return Promise.reject('Fetch did not succeed');
}
})
.then((json) => {
return json.result;
})
.catch(err => console.log(err));
}

With our backend set up, we can import and call calculate() from our frontend:

import { calculate } from 'backend/calculator.jsw';
const calculateButton = $w('#calculate');
calculateButton.onClick((event) => {
const expression = $w('#input').value;
calculate(expression)
.then((result) => {
$w('#result').text = `= ${result}`;
})
});

Having both functions set up, we can now see our calculator widget in action:

My Calculator

When we click the “Calculate” button, the inputted mathematical expression is sent to the math.js API via a POST request (notice how the POST request Content-Type is different from before and that the body containing the expression is stored in JSON format as a string). From there, the API automatically calculates the mathematical expression and returns a JSON object containing the result, which is displayed on the widget.

Similarities and Differences

The boilerplate code for POST, GET, DELETE, and PUT requests look very similar, but it’s important to note that they perform different actions and thus require different properties.

One difference is the method property of the WixFetchRequest object. To make a POST request, we must set the method property to 'post', however, for a GET request, a DELETE request, and a PUT request, it must be set to 'get', 'delete', and 'put' respectively.

A more subtle difference is the content of the body, which depends on whether it’s a POST request, DELETE request, or PUT request.

Wrapping Up

You can now expand your Wix possibilities even further by using the HTTP requests you learned about:

  • Different types of HTTP requests are needed so that websites can allow for different types of user interaction.
  • The DELETE request allows us to remove a specific resource, the GET request allows us to retrieve a specific resource or collection of resources, and the PUT request allows us to update a resource. In this article, we focused on the POST request, which enables us to create a new resource.
  • The POST request uses the Wix fetch() function and its WixFetchRequest argument to send the request method, headers, and body to the server, along with handling the response.

Being equipped with HTTP requests opens many doors — you can now delete, get, update, and send data to the server right from your Wix websites. Go ahead and apply these techniques by contacting an API in different ways or building a social media platform that uses HTTP requests, for example. Or perhaps leave your comfort zone by making a PUT and DELETE request to put your knowledge to the test!

Author

Codecademy Team

'The Codecademy Team, composed of experienced educators and tech experts, is dedicated to making tech skills accessible to all. We empower learners worldwide with expert-reviewed content that develops and enhances the technical skills needed to advance and succeed in their careers.'

Meet the full team