Package to Make Geocode Requests for Flutter

Geocode library

Introduction

Package to make Geocode requests. It exposes two methods to translate coordinates into locations and addresses into coordinates.

It's a basic implementation of the most useful methods in the Dart language of the following API geocode.xyz.

It's free for one request per second quota. Register in the above site to get an API Key and increase the number of requests to 10 per second. These are paid plans that allow more requests per second. For more information, review the site.

Installation

dependecies:
  geocode: 1.0.2

Example

See example/main.dart

import 'package:geocode/geocode.dart';

void main() async {
  GeoCode geoCode = GeoCode();

  try {
    Coordinates coordinates = await geoCode.forwardGeocoding(
        address: "532 S Olive St, Los Angeles, CA 90013");

    print("Latitude: ${coordinates.latitude}");
    print("Longitude: ${coordinates.longitude}");
  } catch (e) {
    print(e);
  }
}

Methods

Constructor

Library GeoCode class constructor, includes an optional parameter to set the apiKey.

GeoCode({this.apiKey});

Reverse Geocode

Method to translate a pair of latitude and longitude coordinates into a real address.

Future<Address> reverseGeocoding({double latitude, double longitude})

Forward Geocode

Method to translate an address into a pair of latitude and longitudecoordinates.

Future<Coordinates> forwardGeocoding({String address})

Responses

Reverse Geocode

AttributeTypeDescription
elevationdoubleThe elevation in meters.
timezoneStringThe timezone.
geoNumberintgeocode is an alphanumeric string representing both latitude and longitude as one value. Nearby points will have similar geocodes.
streetNumberintThe properly formated street address number to be returned.
streetAddressStringThe properly formated street address to be returned.
cityStringThe properly formated city name to be returned.
countyCodeStringThe properly formated country code to be returned.
countryNameStringThe properly formated country name to be returned.
regionStringThe properly formated region to be returned.
postalStringThe properly formated postal code to be returned.
distancedoubleThe distance of the result location from the input location.

Forward Geocode

AttributeTypeDescription
latitudedoubleLatitude coordinate value.
longitudedoubleLongitude coordinate value.

Exceptions

  • AccountOutOfCreditsException: auth has ran out of credits.
  • AuthTokenNotFoundException: authentication token: auth not found.
  • PostalCodeFormatException: postal Code is not in the proper Format.
  • RequestThrottledException: request Throttled.
  • InvalidQueryException: supply a valid query.
  • EmptyResultException: your request did not produce any results. Check your spelling and try again.
  • UnknownErrorException: unkown error.

Dependencies

http: ^0.13.4

License

BSD 3-Clause License

Use this package as a library

Depend on it

Run this command:

With Dart:

 $ dart pub add geocode

With Flutter:

 $ flutter pub add geocode

This will add a line like this to your package's pubspec.yaml (and run an implicit dart pub get):

dependencies:
  geocode: ^1.0.2

Alternatively, your editor might support dart pub get or flutter pub get. Check the docs for your editor to learn more.

Import it

Now in your Dart code, you can use:

import 'package:geocode/geocode.dart';

example/main.dart

import 'package:geocode/geocode.dart';

void main() async {
  GeoCode geoCode = GeoCode();

  try {
    Coordinates coordinates = await geoCode.forwardGeocoding(
        address: "532 S Olive St, Los Angeles, CA 90013");

    print("Latitude: ${coordinates.latitude}");
    print("Longitude: ${coordinates.longitude}");
  } catch (e) {
    print(e);
  }
}

Download Details:

Author: imanol.dev

Source Code: https://github.com/imvalient/geocode

#flutter #android #ios #geocoding #request 

Package to Make Geocode Requests for Flutter

Запрос получения JavaScript

При создании приложений вам придется взаимодействовать между бэкэндом и интерфейсом для получения, хранения и обработки данных.

Это взаимодействие между вашим внешним приложением и внутренним сервером возможно через HTTP-запросы.

Существует пять популярных методов HTTP, которые вы можете использовать для выполнения запросов и взаимодействия с вашими серверами. Одним из методов HTTP является метод GET, который может получать данные с вашего сервера.

В этой статье вы узнаете, как запрашивать данные с ваших серверов с помощью GET-запроса. Вы познакомитесь с популярными методами, существующими в настоящее время, и некоторыми другими альтернативными методами.

В этом руководстве мы будем извлекать сообщения из бесплатного API сообщений JSON Placeholder .

Есть два популярных метода, которые вы можете легко использовать для выполнения HTTP-запросов в JavaScript. Это Fetch API и Axios.

Как сделать запрос GET с помощью Fetch API

Fetch API — это встроенный метод JavaScript для извлечения ресурсов и взаимодействия с внутренним сервером или конечной точкой API. Fetch API встроен и не требует установки в ваш проект.

Fetch API принимает один обязательный аргумент: конечную точку/URL API. Этот метод также принимает аргумент option , который является необязательным объектом при выполнении запроса GET, поскольку он является запросом по умолчанию .

  fetch(url, {
      method: "GET" // default, so we can ignore
  })

Давайте создадим GET-запрос, чтобы получить сообщение из JSON Placeholder posts API .

fetch("https://jsonplaceholder.typicode.com/posts/1")
  .then((response) => response.json())
  .then((json) => console.log(json));

Это вернет один пост, который вы теперь можете сохранить в переменной и использовать в своем проекте.

Примечание. Для других методов, таких как POST и DELETE, вам необходимо присоединить метод к массиву параметров.

Как сделать запрос GET с помощью Axios

Axios — это клиентская библиотека HTTP. Эта библиотека основана на обещаниях, которые упрощают отправку асинхронных HTTP-запросов на конечные точки REST. Мы отправим запрос GET на конечную точку JSONPlaceholder Posts API.

Axios, в отличие от Fetch API, не является встроенным. Это означает, что вам нужно установить Axios в свой проект JavaScript.

Чтобы установить зависимость в свой проект JavaScript, вы сначала инициализируете новый npmпроект, выполнив следующую команду в своем терминале:

$ npm init -y

И теперь вы можете установить Axios в свой проект, выполнив следующую команду:

$ npm install axios

После успешной установки Axios вы можете создать запрос GET. Это очень похоже на запрос Fetch API. Вы передадите конечную точку/URL API методу get(), который вернет обещание. Затем вы можете обработать обещание с помощью методов .then()и .catch().

axios.get("https://jsonplaceholder.typicode.com/posts/1")
.then((response) => console.log(response.data))
.catch((error) => console.log(error));

Примечание. Основное отличие заключается в том, что для Fetch API вы сначала конвертируете данные в JSON, а Axios возвращает ваши данные непосредственно в виде данных JSON.

К этому моменту вы узнали, как сделать HTTP-запрос GET с помощью Fetch API и Axios. Но есть и другие методы, которые все еще существуют. Некоторыми из этих методов являются XMLHttpRequest и jQuery.

Как сделать запрос GET с помощьюXMLHttpRequest

Вы можете использовать объект XMLHttpRequest для взаимодействия с серверами. Этот метод может запрашивать данные из конечной точки/URL API веб-сервера без полного обновления страницы.

Примечание. Все современные браузеры имеют встроенный объект XMLHttpRequest для запроса данных с сервера.

Давайте выполним тот же запрос с XMLHttpRequest, создав новый объект XMLHttpRequest. Затем вы откроете соединение, указав тип запроса и конечную точку (URL-адрес сервера), затем отправите запрос и, наконец, прослушаете ответ сервера.

const xhr = new XMLHttpRequest();
xhr.open("GET", "https://jsonplaceholder.typicode.com/posts/1");
xhr.send();
xhr.responseType = "json";
xhr.onload = () => {
  if (xhr.readyState == 4 && xhr.status == 200) {
    console.log(xhr.response);
  } else {
    console.log(`Error: ${xhr.status}`);
  }
};

В приведенном выше коде создается новый объект XMLHttpRequest, который сохраняется в переменной с именем xhr. Теперь вы можете получить доступ ко всем его объектам с помощью переменной, такой как .open()метод, когда вы указываете тип запроса (GET) и конечную точку/URL, где вы хотите запросить данные.

Другой метод, который вы будете использовать .send(), — это отправка запроса на сервер. Вы также можете указать формат, в котором данные будут возвращены с помощью responseTypeметода. В этот момент отправляется запрос GET, и все, что вам нужно сделать, это прослушать его ответ с помощью onloadпрослушивателя событий.

Если состояние клиента выполнено ( 4) и код состояния успешен ( 200) , то данные будут записаны в консоль. В противном случае появится сообщение об ошибке, показывающее статус ошибки.

Как сделать запрос GET с помощью jQuery

Выполнение HTTP-запросов в jQuery относительно просто и похоже на Fetch API и Axios. Чтобы сделать запрос GET, вы должны сначала установить jQuery или использовать его CDN в своем проекте:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.2/jquery.min.js" integrity="sha512-tWHlutFnuG0C6nQRlpvrEhE4QpkG1nn2MOUMWmUeRePl4e3Aki0VB6W1v3oLjFtd0hVOtRQ9PHpSfN6u6/QXkQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

С помощью jQuery вы можете получить доступ к методу GET $.get(), который принимает два параметра: конечную точку/URL API и функцию обратного вызова, которая запускается при успешном выполнении запроса.

$.get("https://jsonplaceholder.typicode.com/posts/1", (data, status) => {
  console.log(data);
});

Примечание. В функции обратного вызова у вас есть доступ к данным запроса и статусу запроса .

Вы также можете использовать метод jQuery AJAX, который сильно отличается и может использоваться для выполнения асинхронных запросов:

$.ajax({
  url: "https://jsonplaceholder.typicode.com/posts/1",
  type: "GET",
  success: function (data) {
    console.log(data);
  }
});

Подведение итогов

В этой статье вы узнали, как сделать запрос HTTP GET в JavaScript. Теперь вы можете начать думать — какой метод мне следует использовать?

Если это новый проект, вы можете выбрать между Fetch API и Axios. Кроме того, если вы хотите использовать базовые API для небольшого проекта, нет необходимости использовать Axios, который требует установки библиотеки.

Получайте удовольствие от кодирования!

Оригинальный источник статьи: https://www.freecodecamp.org/

#javascript #request 

Запрос получения JavaScript
木村  直子

木村 直子

1681200000

JavaScript 获取请求

在构建应用程序时,您将不得不在后端和前端之间进行交互以获取、存储和操作数据。

前端应用程序和后端服务器之间的这种交互可以通过 HTTP 请求实现。

您可以使用五种流行的 HTTP 方法来发出请求并与服务器交互。一种 HTTP 方法是 GET 方法,它可以从您的服务器检索数据。

本文将教您如何通过发出 GET 请求从您的服务器请求数据。您将学习当前存在的流行方法和其他一些替代方法。

对于本指南,我们将从免费的JSON Placeholder 帖子 API中检索帖子。

您可以轻松使用两种流行的方法在 JavaScript 中发出 HTTP 请求。这些是 Fetch API 和 Axios。

如何使用 Fetch API 发出 GET 请求

Fetch API 是一种内置的 JavaScript 方法,用于检索资源并与后端服务器或 API 端点进行交互。Fetch API 是内置的,不需要安装到您的项目中。

Fetch API 接受一个强制参数:API 端点/URL。此方法还接受一个选项参数,该参数在发出 GET 请求时是一个可选对象,因为它是默认请求

  fetch(url, {
      method: "GET" // default, so we can ignore
  })

让我们创建一个 GET 请求以从JSON Placeholder posts API获取帖子。

fetch("https://jsonplaceholder.typicode.com/posts/1")
  .then((response) => response.json())
  .then((json) => console.log(json));

这将返回一个帖子,您现在可以将其存储在一个变量中并在您的项目中使用。

注意:对于其他方法,例如 POST 和 DELETE,您需要将方法附加到选项数组。

如何使用 Axios 发出 GET 请求

Axios 是一个 HTTP 客户端库。该库基于简化向 REST 端点发送异步 HTTP 请求的承诺。我们将向 JSONPlaceholder Posts API 端点发送 GET 请求。

与 Fetch API 不同,Axios 不是内置的。这意味着您需要将 Axios 安装到您的 JavaScript 项目中。

要将依赖项安装到您的 JavaScript 项目中,您将首先npm通过在终端中运行以下命令来初始化一个新项目:

$ npm init -y

现在您可以通过运行以下命令将 Axios 安装到您的项目中:

$ npm install axios

成功安装 Axios 后,您可以创建 GET 请求。这与 Fetch API 请求非常相似。您将 API 端点/URL 传递给该get()方法,该方法将返回一个承诺。.then()然后,您可以使用和方法处理承诺.catch()

axios.get("https://jsonplaceholder.typicode.com/posts/1")
.then((response) => console.log(response.data))
.catch((error) => console.log(error));

注意:主要区别在于,对于 Fetch API,您首先将数据转换为 JSON,而 Axios 直接将您的数据作为 JSON 数据返回。

至此,您已经了解了如何使用 Fetch API 和 Axios 发出 GET HTTP 请求。但是还有一些其他方法仍然存在。其中一些方法是XMLHttpRequest和 jQuery。

如何使用 GET 请求XMLHttpRequest

您可以使用 XMLHttpRequest 对象与服务器交互。此方法可以从 Web 服务器的 API 端点/URL 请求数据,而无需刷新整个页面。

注意:所有现代浏览器都有一个内置的 XMLHttpRequest 对象来从服务器请求数据。

让我们通过创建一个新的 XMLHttpRequest 对象来使用 XMLHttpRequest 执行相同的请求。然后,您将通过指定请求类型和端点(服务器的 URL)打开一个连接,然后您将发送请求,最后收听服务器的响应。

const xhr = new XMLHttpRequest();
xhr.open("GET", "https://jsonplaceholder.typicode.com/posts/1");
xhr.send();
xhr.responseType = "json";
xhr.onload = () => {
  if (xhr.readyState == 4 && xhr.status == 200) {
    console.log(xhr.response);
  } else {
    console.log(`Error: ${xhr.status}`);
  }
};

在上面的代码中,创建了一个新的 XMLHttpRequest 对象并将其存储在一个名为xhr. .open()当您指定请求类型 (GET) 和要请求数据的端点/URL 时,您现在可以使用变量访问其所有对象,例如方法。

您将使用的另一种方法是.send(),它将请求发送到服务器。您还可以指定使用该方法返回数据的格式responseType。此时,GET 请求已发送,您所要做的就是使用onload事件侦听器侦听其响应。

如果客户端的状态为完成 ( 4),并且状态代码为成功 ( 200),则数据将被记录到控制台。否则,将出现显示错误状态的错误消息。

如何使用 jQuery 发出 GET 请求

在 jQuery 中发出 HTTP 请求相对简单,类似于 Fetch API 和 Axios。要发出 GET 请求,您将首先安装 jQuery 或在您的项目中使用它的 CDN:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.2/jquery.min.js" integrity="sha512-tWHlutFnuG0C6nQRlpvrEhE4QpkG1nn2MOUMWmUeRePl4e3Aki0VB6W1v3oLjFtd0hVOtRQ9PHpSfN6u6/QXkQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

使用 jQuery,您可以访问 GET 方法$.get(),该方法接受两个参数,即 API 端点/URL 和一个在请求成功时运行的回调函数。

$.get("https://jsonplaceholder.typicode.com/posts/1", (data, status) => {
  console.log(data);
});

注意:在回调函数中,您可以访问请求的数据和请求的状态

您还可以使用 jQuery AJAX 方法,它非常不同,可用于发出异步请求:

$.ajax({
  url: "https://jsonplaceholder.typicode.com/posts/1",
  type: "GET",
  success: function (data) {
    console.log(data);
  }
});

包起来

在本文中,您学习了如何在 JavaScript 中发出 HTTP GET 请求。您现在可能会开始思考——我应该使用哪种方法?

如果是新项目,可以在 Fetch API 和 Axios 之间选择。另外,如果你想为一个小项目使用基本的API,就不需要使用Axios,它需要安装一个库。

享受编码乐趣!

文章原文出处:https: //www.freecodecamp.org/

#javascript #request 

JavaScript 获取请求

JavaScript Get Request

When building applications, you will have to interact between the backend and frontend to get, store, and manipulate data.

This interaction between your frontend application and the backend server is possible through HTTP requests.

There are five popular HTTP methods you can use to make requests and interact with your servers. One HTTP method is the GET method, which can retrieve data from your server.

This article will teach you how to request data from your servers by making a GET request. You will learn the popular methods that exist currently and some other alternative methods.

For this guide, we'll retrieve posts from the free JSON Placeholder posts API.

There are two popular methods you can easily use to make HTTP requests in JavaScript. These are the Fetch API and Axios.

How to Make a GET Request with the Fetch API

The Fetch API is a built-in JavaScript method for retrieving resources and interacting with your backend server or an API endpoint. Fetch API is built-in and does not require installation into your project.

Fetch API accepts one mandatory argument: the API endpoint/URL. This method also accepts an option argument, which is an optional object when making a GET request because it is the default request.

  fetch(url, {
      method: "GET" // default, so we can ignore
  })

Let’s create a GET request to get a post from the JSON Placeholder posts API.

fetch("https://jsonplaceholder.typicode.com/posts/1")
  .then((response) => response.json())
  .then((json) => console.log(json));

This will return a single post which you can now store in a variable and use within your project.

Note: For other methods, such as POST and DELETE, you need to attach the method to the options array.

How to Make a GET Request with Axios

Axios is an HTTP client library. This library is based on promises that simplify sending asynchronous HTTP requests to REST endpoints. We will send a GET request to the JSONPlaceholder Posts API endpoint.

Axios, unlike the Fetch API, is not built-in. This means you need to install Axios into your JavaScript project.

To install a dependency into your JavaScript project, you will first initialize a new npm project by running the following command in your terminal:

$ npm init -y

And now you can install Axios to your project by running the following command:

$ npm install axios

Once Axios is successfully installed, you can create your GET request. This is quite similar to the Fetch API request. You will pass the API endpoint/URL to the get() method, which will return a promise. You can then handle the promise with the .then() and .catch() methods.

axios.get("https://jsonplaceholder.typicode.com/posts/1")
.then((response) => console.log(response.data))
.catch((error) => console.log(error));

Note: The major difference is that, for Fetch API, you first convert the data to JSON, while Axios returns your data directly as JSON data.

At this point, you have learned how to make a GET HTTP request with Fetch API and Axios. But there are some other methods that still exist. Some of these methods are XMLHttpRequest and jQuery.

How to Make a GET Request with XMLHttpRequest

You can use the XMLHttpRequest object to interact with servers. This method can request data from a web server’s API endpoint/URL without doing a full page refresh.

Note: All modern browsers have a built-in XMLHttpRequest object to request data from a server.

Let’s perform the same request with the XMLHttpRequest by creating a new XMLHttpRequest object. You will then open a connection by specifying the request type and endpoint (the URL of the server), then you'll send the request, and finally listen to the server’s response.

const xhr = new XMLHttpRequest();
xhr.open("GET", "https://jsonplaceholder.typicode.com/posts/1");
xhr.send();
xhr.responseType = "json";
xhr.onload = () => {
  if (xhr.readyState == 4 && xhr.status == 200) {
    console.log(xhr.response);
  } else {
    console.log(`Error: ${xhr.status}`);
  }
};

In the above code, a new XMLHttpRequest object is created and stored in a variable called xhr. You can now access all its objects using the variable, such as the .open() method, when you specify the request type (GET) and the endpoint/URL where you want to request data.

Another method you will use is .send(), which sends the request to the server. You can also specify the format in which the data will be returned using the responseType method. At this point, the GET request is sent, and all you have to do is listen to its response using the onload event listener.

If the client's state is done (4), and the status code is successful (200), then the data will be logged to the console. Otherwise, an error message showing the error status will appear.

How to Make a GET Request with jQuery

Making HTTP requests in jQuery is relatively straightforward and similar to the Fetch API and Axios. To make a GET request, you will first install jQuery or make use of its CDN in your project:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.2/jquery.min.js" integrity="sha512-tWHlutFnuG0C6nQRlpvrEhE4QpkG1nn2MOUMWmUeRePl4e3Aki0VB6W1v3oLjFtd0hVOtRQ9PHpSfN6u6/QXkQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

With jQuery, you can access the GET method $.get(), which takes in two parameters, the API endpoint/URL and a callback function that runs when the request is successful.

$.get("https://jsonplaceholder.typicode.com/posts/1", (data, status) => {
  console.log(data);
});

Note: In the callback function, you have access to the request's data and the request's status.

You can also use the jQuery AJAX Method, which is quite different and can be used to make asynchronous requests:

$.ajax({
  url: "https://jsonplaceholder.typicode.com/posts/1",
  type: "GET",
  success: function (data) {
    console.log(data);
  }
});

Wrapping Up

In this article, you have learned how to make the HTTP GET request in JavaScript. You might now begin to think — which method should I use?

If it’s a new project, you can choose between the Fetch API and Axios. Also, if you want to consume basic APIs for a small project, there is no need to use Axios, which demands installing a library.

Have fun coding!

Original article source at: https://www.freecodecamp.org/

#javascript #request 

JavaScript Get Request

Как сделать HTTP-запрос в JavaScript

При создании приложений вам придется взаимодействовать между бэкэндом и интерфейсом для получения, хранения и обработки данных.

Это взаимодействие между вашим внешним приложением и внутренним сервером возможно через HTTP-запросы.

Существует пять популярных методов HTTP, которые вы можете использовать для отправки запросов и взаимодействия с вашими серверами. Одним из методов HTTP является метод GET, который может получать данные с вашего сервера.

В этой статье вы узнаете, как запрашивать данные с ваших серверов с помощью GET-запроса. Вы познакомитесь с популярными методами, существующими в настоящее время, и некоторыми другими альтернативными методами.

В этом руководстве мы будем извлекать сообщения из бесплатного API сообщений JSON Placeholder .

Есть два популярных метода, которые вы можете легко использовать для выполнения HTTP-запросов в JavaScript. Это Fetch API и Axios.

Как сделать запрос GET с помощью Fetch API

Fetch API — это встроенный метод JavaScript для извлечения ресурсов и взаимодействия с внутренним сервером или конечной точкой API. Fetch API встроен и не требует установки в ваш проект.

Fetch API принимает один обязательный аргумент: конечную точку/URL API. Этот метод также принимает аргумент option , который является необязательным объектом при выполнении запроса GET, поскольку он является запросом по умолчанию .

  fetch(url, {
      method: "GET" // default, so we can ignore
  })

Давайте создадим GET-запрос, чтобы получить сообщение из JSON Placeholder posts API .

fetch("https://jsonplaceholder.typicode.com/posts/1")
  .then((response) => response.json())
  .then((json) => console.log(json));

Это вернет один пост, который вы теперь можете сохранить в переменной и использовать в своем проекте.

Примечание. Для других методов, таких как POST и DELETE, вам необходимо присоединить метод к массиву параметров.

Как сделать запрос GET с помощью Axios

Axios — это клиентская библиотека HTTP. Эта библиотека основана на обещаниях, которые упрощают отправку асинхронных HTTP-запросов на конечные точки REST. Мы отправим запрос GET на конечную точку JSONPlaceholder Posts API.

Axios, в отличие от Fetch API, не является встроенным. Это означает, что вам нужно установить Axios в свой проект JavaScript.

Чтобы установить зависимость в свой проект JavaScript, вы сначала инициализируете новый npmпроект, выполнив следующую команду в своем терминале:

$ npm init -y

И теперь вы можете установить Axios в свой проект, выполнив следующую команду:

$ npm install axios

После успешной установки Axios вы можете создать запрос GET. Это очень похоже на запрос Fetch API. Вы передадите конечную точку/URL API методу get(), который вернет обещание. Затем вы можете обработать обещание с помощью методов .then()и .catch().

axios.get("https://jsonplaceholder.typicode.com/posts/1")
.then((response) => console.log(response.data))
.catch((error) => console.log(error));

Примечание. Основное отличие заключается в том, что для Fetch API вы сначала конвертируете данные в JSON, а Axios возвращает ваши данные непосредственно в виде данных JSON.

К этому моменту вы узнали, как сделать HTTP-запрос GET с помощью Fetch API и Axios. Но есть и другие методы, которые все еще существуют. Некоторыми из этих методов являются XMLHttpRequest и jQuery.

Как сделать запрос GET с помощьюXMLHttpRequest

Вы можете использовать объект XMLHttpRequest для взаимодействия с серверами. Этот метод может запрашивать данные из конечной точки/URL API веб-сервера без полного обновления страницы.

Примечание. Все современные браузеры имеют встроенный объект XMLHttpRequest для запроса данных с сервера.

Давайте выполним тот же запрос с XMLHttpRequest, создав новый объект XMLHttpRequest. Затем вы откроете соединение, указав тип запроса и конечную точку (URL-адрес сервера), затем отправите запрос и, наконец, прослушаете ответ сервера.

const xhr = new XMLHttpRequest();
xhr.open("GET", "https://jsonplaceholder.typicode.com/posts/1");
xhr.send();
xhr.responseType = "json";
xhr.onload = () => {
  if (xhr.readyState == 4 && xhr.status == 200) {
    console.log(xhr.response);
  } else {
    console.log(`Error: ${xhr.status}`);
  }
};

В приведенном выше коде создается новый объект XMLHttpRequest, который сохраняется в переменной с именем xhr. Теперь вы можете получить доступ ко всем его объектам с помощью переменной, такой как .open()метод, когда вы указываете тип запроса (GET) и конечную точку/URL, где вы хотите запросить данные.

Другой метод, который вы будете использовать .send(), — это отправка запроса на сервер. Вы также можете указать формат, в котором данные будут возвращены с помощью responseTypeметода. В этот момент отправляется запрос GET, и все, что вам нужно сделать, это прослушать его ответ с помощью onloadпрослушивателя событий.

Если состояние клиента выполнено ( 4) и код состояния успешен ( 200) , то данные будут записаны в консоль. В противном случае появится сообщение об ошибке, показывающее статус ошибки.

Как сделать запрос GET с помощью jQuery

Выполнение HTTP-запросов в jQuery относительно просто и похоже на Fetch API и Axios. Чтобы сделать запрос GET, вы должны сначала установить jQuery или использовать его CDN в своем проекте:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.2/jquery.min.js" integrity="sha512-tWHlutFnuG0C6nQRlpvrEhE4QpkG1nn2MOUMWmUeRePl4e3Aki0VB6W1v3oLjFtd0hVOtRQ9PHpSfN6u6/QXkQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

С помощью jQuery вы можете получить доступ к методу GET $.get(), который принимает два параметра: конечную точку/URL API и функцию обратного вызова, которая запускается при успешном выполнении запроса.

$.get("https://jsonplaceholder.typicode.com/posts/1", (data, status) => {
  console.log(data);
});

Примечание. В функции обратного вызова у вас есть доступ к данным запроса и статусу запроса .

Вы также можете использовать метод jQuery AJAX, который сильно отличается и может использоваться для выполнения асинхронных запросов:

$.ajax({
  url: "https://jsonplaceholder.typicode.com/posts/1",
  type: "GET",
  success: function (data) {
    console.log(data);
  }
});

Подведение итогов

В этой статье вы узнали, как сделать запрос HTTP GET в JavaScript. Теперь вы можете начать думать — какой метод мне следует использовать?

Если это новый проект, вы можете выбрать между Fetch API и Axios. Кроме того, если вы хотите использовать базовые API для небольшого проекта, нет необходимости использовать Axios, который требует установки библиотеки.

Получайте удовольствие от кодирования!

Оригинальный источник статьи: https://www.freecodecamp.org/

#javascript #http #request 

Как сделать HTTP-запрос в JavaScript
佐藤  桃子

佐藤 桃子

1680744360

如何在 JavaScript 中发起 HTTP 请求

在构建应用程序时,您将不得不在后端和前端之间进行交互以获取、存储和操作数据。

前端应用程序和后端服务器之间的这种交互可以通过 HTTP 请求实现。

您可以使用五种流行的 HTTP 方法来发出请求并与服务器交互。一种 HTTP 方法是 GET 方法,它可以从您的服务器检索数据。

本文将教您如何通过发出 GET 请求从您的服务器请求数据。您将学习当前存在的流行方法和其他一些替代方法。

对于本指南,我们将从免费的JSON Placeholder 帖子 API中检索帖子。

您可以轻松使用两种流行的方法在 JavaScript 中发出 HTTP 请求。这些是 Fetch API 和 Axios。

如何使用 Fetch API 发出 GET 请求

Fetch API 是一种内置的 JavaScript 方法,用于检索资源并与后端服务器或 API 端点进行交互。Fetch API 是内置的,不需要安装到您的项目中。

Fetch API 接受一个强制参数:API 端点/URL。此方法还接受一个选项参数,该参数在发出 GET 请求时是一个可选对象,因为它是默认请求

  fetch(url, {
      method: "GET" // default, so we can ignore
  })

让我们创建一个 GET 请求以从JSON Placeholder posts API获取帖子。

fetch("https://jsonplaceholder.typicode.com/posts/1")
  .then((response) => response.json())
  .then((json) => console.log(json));

这将返回一个帖子,您现在可以将其存储在一个变量中并在您的项目中使用。

注意:对于其他方法,例如 POST 和 DELETE,您需要将方法附加到选项数组。

如何使用 Axios 发出 GET 请求

Axios 是一个 HTTP 客户端库。该库基于简化向 REST 端点发送异步 HTTP 请求的承诺。我们将向 JSONPlaceholder Posts API 端点发送 GET 请求。

与 Fetch API 不同,Axios 不是内置的。这意味着您需要将 Axios 安装到您的 JavaScript 项目中。

要将依赖项安装到您的 JavaScript 项目中,您将首先npm通过在终端中运行以下命令来初始化一个新项目:

$ npm init -y

现在您可以通过运行以下命令将 Axios 安装到您的项目中:

$ npm install axios

成功安装 Axios 后,您可以创建 GET 请求。这与 Fetch API 请求非常相似。您将 API 端点/URL 传递给该get()方法,该方法将返回一个承诺。.then()然后,您可以使用和方法处理承诺.catch()

axios.get("https://jsonplaceholder.typicode.com/posts/1")
.then((response) => console.log(response.data))
.catch((error) => console.log(error));

注意:主要区别在于,对于 Fetch API,您首先将数据转换为 JSON,而 Axios 直接将您的数据作为 JSON 数据返回。

至此,您已经了解了如何使用 Fetch API 和 Axios 发出 GET HTTP 请求。但是还有一些其他方法仍然存在。其中一些方法是XMLHttpRequest和 jQuery。

如何使用 GET 请求XMLHttpRequest

您可以使用 XMLHttpRequest 对象与服务器交互。此方法可以从 Web 服务器的 API 端点/URL 请求数据,而无需刷新整个页面。

注意:所有现代浏览器都有一个内置的 XMLHttpRequest 对象来从服务器请求数据。

让我们通过创建一个新的 XMLHttpRequest 对象来使用 XMLHttpRequest 执行相同的请求。然后,您将通过指定请求类型和端点(服务器的 URL)打开一个连接,然后您将发送请求,最后收听服务器的响应。

const xhr = new XMLHttpRequest();
xhr.open("GET", "https://jsonplaceholder.typicode.com/posts/1");
xhr.send();
xhr.responseType = "json";
xhr.onload = () => {
  if (xhr.readyState == 4 && xhr.status == 200) {
    console.log(xhr.response);
  } else {
    console.log(`Error: ${xhr.status}`);
  }
};

在上面的代码中,创建了一个新的 XMLHttpRequest 对象并将其存储在一个名为xhr. .open()当您指定请求类型 (GET) 和要请求数据的端点/URL 时,您现在可以使用变量访问其所有对象,例如方法。

您将使用的另一种方法是.send(),它将请求发送到服务器。您还可以使用该方法指定返回数据的格式responseType。此时,GET 请求已发送,您所要做的就是使用onload事件侦听器侦听其响应。

如果客户端的状态为完成 ( 4),并且状态代码为成功 ( 200),则数据将被记录到控制台。否则,将出现显示错误状态的错误消息。

如何使用 jQuery 发出 GET 请求

在 jQuery 中发出 HTTP 请求相对简单,类似于 Fetch API 和 Axios。要发出 GET 请求,您将首先安装 jQuery 或在您的项目中使用它的 CDN:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.2/jquery.min.js" integrity="sha512-tWHlutFnuG0C6nQRlpvrEhE4QpkG1nn2MOUMWmUeRePl4e3Aki0VB6W1v3oLjFtd0hVOtRQ9PHpSfN6u6/QXkQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

使用 jQuery,您可以访问 GET 方法$.get(),该方法接受两个参数,即 API 端点/URL 和一个在请求成功时运行的回调函数。

$.get("https://jsonplaceholder.typicode.com/posts/1", (data, status) => {
  console.log(data);
});

注意:在回调函数中,您可以访问请求的数据和请求的状态

您还可以使用 jQuery AJAX 方法,它非常不同,可用于发出异步请求:

$.ajax({
  url: "https://jsonplaceholder.typicode.com/posts/1",
  type: "GET",
  success: function (data) {
    console.log(data);
  }
});

包起来

在本文中,您学习了如何在 JavaScript 中发出 HTTP GET 请求。您现在可能会开始思考——我应该使用哪种方法?

如果是新项目,可以在 Fetch API 和 Axios 之间选择。另外,如果你想为一个小项目使用基本的API,就不需要使用Axios,它需要安装一个库。

享受编码乐趣!

文章原文出处:https: //www.freecodecamp.org/

#javascript #http #request 

如何在 JavaScript 中发起 HTTP 请求

How to Make an HTTP Request in JavaScript

When building applications, you will have to interact between the backend and frontend to get, store, and manipulate data.

This interaction between your frontend application and the backend server is possible through HTTP requests.

There are five popular HTTP methods you can use to make requests and interact with your servers. One HTTP method is the GET method, which can retrieve data from your server.

This article will teach you how to request data from your servers by making a GET request. You will learn the popular methods that exist currently and some other alternative methods.

For this guide, we'll retrieve posts from the free JSON Placeholder posts API.

There are two popular methods you can easily use to make HTTP requests in JavaScript. These are the Fetch API and Axios.

How to Make a GET Request with the Fetch API

The Fetch API is a built-in JavaScript method for retrieving resources and interacting with your backend server or an API endpoint. Fetch API is built-in and does not require installation into your project.

Fetch API accepts one mandatory argument: the API endpoint/URL. This method also accepts an option argument, which is an optional object when making a GET request because it is the default request.

  fetch(url, {
      method: "GET" // default, so we can ignore
  })

Let’s create a GET request to get a post from the JSON Placeholder posts API.

fetch("https://jsonplaceholder.typicode.com/posts/1")
  .then((response) => response.json())
  .then((json) => console.log(json));

This will return a single post which you can now store in a variable and use within your project.

Note: For other methods, such as POST and DELETE, you need to attach the method to the options array.

How to Make a GET Request with Axios

Axios is an HTTP client library. This library is based on promises that simplify sending asynchronous HTTP requests to REST endpoints. We will send a GET request to the JSONPlaceholder Posts API endpoint.

Axios, unlike the Fetch API, is not built-in. This means you need to install Axios into your JavaScript project.

To install a dependency into your JavaScript project, you will first initialize a new npm project by running the following command in your terminal:

$ npm init -y

And now you can install Axios to your project by running the following command:

$ npm install axios

Once Axios is successfully installed, you can create your GET request. This is quite similar to the Fetch API request. You will pass the API endpoint/URL to the get() method, which will return a promise. You can then handle the promise with the .then() and .catch() methods.

axios.get("https://jsonplaceholder.typicode.com/posts/1")
.then((response) => console.log(response.data))
.catch((error) => console.log(error));

Note: The major difference is that, for Fetch API, you first convert the data to JSON, while Axios returns your data directly as JSON data.

At this point, you have learned how to make a GET HTTP request with Fetch API and Axios. But there are some other methods that still exist. Some of these methods are XMLHttpRequest and jQuery.

How to Make a GET Request with XMLHttpRequest

You can use the XMLHttpRequest object to interact with servers. This method can request data from a web server’s API endpoint/URL without doing a full page refresh.

Note: All modern browsers have a built-in XMLHttpRequest object to request data from a server.

Let’s perform the same request with the XMLHttpRequest by creating a new XMLHttpRequest object. You will then open a connection by specifying the request type and endpoint (the URL of the server), then you'll send the request, and finally listen to the server’s response.

const xhr = new XMLHttpRequest();
xhr.open("GET", "https://jsonplaceholder.typicode.com/posts/1");
xhr.send();
xhr.responseType = "json";
xhr.onload = () => {
  if (xhr.readyState == 4 && xhr.status == 200) {
    console.log(xhr.response);
  } else {
    console.log(`Error: ${xhr.status}`);
  }
};

In the above code, a new XMLHttpRequest object is created and stored in a variable called xhr. You can now access all its objects using the variable, such as the .open() method, when you specify the request type (GET) and the endpoint/URL where you want to request data.

Another method you will use is .send(), which sends the request to the server. You can also specify the format in which the data will be returned using the responseType method. At this point, the GET request is sent, and all you have to do is listen to its response using the onload event listener.

If the client's state is done (4), and the status code is successful (200), then the data will be logged to the console. Otherwise, an error message showing the error status will appear.

How to Make a GET Request with jQuery

Making HTTP requests in jQuery is relatively straightforward and similar to the Fetch API and Axios. To make a GET request, you will first install jQuery or make use of its CDN in your project:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.2/jquery.min.js" integrity="sha512-tWHlutFnuG0C6nQRlpvrEhE4QpkG1nn2MOUMWmUeRePl4e3Aki0VB6W1v3oLjFtd0hVOtRQ9PHpSfN6u6/QXkQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

With jQuery, you can access the GET method $.get(), which takes in two parameters, the API endpoint/URL and a callback function that runs when the request is successful.

$.get("https://jsonplaceholder.typicode.com/posts/1", (data, status) => {
  console.log(data);
});

Note: In the callback function, you have access to the request's data and the request's status.

You can also use the jQuery AJAX Method, which is quite different and can be used to make asynchronous requests:

$.ajax({
  url: "https://jsonplaceholder.typicode.com/posts/1",
  type: "GET",
  success: function (data) {
    console.log(data);
  }
});

Wrapping Up

In this article, you have learned how to make the HTTP GET request in JavaScript. You might now begin to think — which method should I use?

If it’s a new project, you can choose between the Fetch API and Axios. Also, if you want to consume basic APIs for a small project, there is no need to use Axios, which demands installing a library.

Have fun coding!

Original article source at: https://www.freecodecamp.org/

#javascript #http #request 

How to Make an HTTP Request in JavaScript

Make A POST Request with cURL

Make A POST Request with cURL

cURL is a command-line utility for transferring data from or to a remote server using one of the supported protocols. It is installed by default on macOS and most Linux distributions.

cURL is used by developers for testing APIs , viewing response headers, and making HTTP requests.

In this article, we’re going to explain how to use cURL to make POST requests. The HTTP POST method is used to send data to the remote server.

Making a POST request

The general form of the curl command for making a POST request is as follows:

curl -X POST [options] [URL]

The -X option specifies which HTTP request method will be used when communicating with the remote server.

The type of the request body is indicated by its Content-Type header.

Generally, a POST request is sent via an HTML form. The data send to the form is usually encoded in either multipart/form-data or application/x-www-form-urlencoded content type.

To create a POST request, use the -F option, followed by the field=value pair. The following example shows how to make a POST request to a form that has “name” and “email” fields:

curl -X POST -F 'name=linuxize' -F 'email=linuxize@example.com' https://example.com/contact.php

When the -F option is used, curl sends the data using the multipart/form-data Content-Type.

Another way to make a POST request is to use the -d option. This causes curl to send the data using the application/x-www-form-urlencoded Content-Type.

curl -X POST -d 'name=linuxize' -d 'email=linuxize@example.com' https://example.com/contact.php

If the -d option is used more than once you can merge the data using the & symbol:

curl -X POST -d 'name=linuxize&email=linuxize@example.com' https://example.com/contact.php

Specifying the Content-Type

To set a specific header or Content-Type use the -H option. The following command sets the POST request type to application/json and sends a JSON object:

curl -X POST -H "Content-Type: application/json" \
    -d '{"name": "linuxize", "email": "linuxize@example.com"}' \
    https://example/contact

Uploading Files

To POST a file with curl, simply add the @ symbol before the file location. The file can be an archive, image, document, etc.

curl -X POST -F 'image=@/home/user/Pictures/wallpaper.jpg' http://example.com/upload

Conclusion

We’ve shown you how to use curl to make POST requests. For more information about curl, visit the Curl Documentation page.

If you have any questions or feedback, feel free to leave a comment.

Original article source at: https://linuxize.com/

#curl #post #request #terminal 

Make A POST Request with cURL

Send Headers With an Axios POST Request

Send Headers With an Axios POST Request

Introduction

Axios is an HTTP client library that is used to send asynchronous HTTP requests such as POST, GET, and DELETE to REST endpoints (mainly APIs). Some of these requests, such as GET and POST, can include headers, which provide an additional source of information for each API call.

In this article, we will learn how to send headers alongside our POST request in Axios.

Headers are critical when making API requests and are one of the first places we look when we encounter problems with an API because they help us track down any potential issues.

POST Request Structure In Axios

An Axios POST request can accept three parameters: the endpoint's URL, data, and the configuration object, which accepts headers:

const res = await axios.post(URL, data, config);

Sending Headers With Axios POST Request

When passing headers into Axios, we supply an object containing the headers we want to pass as the config parameter. For example, assume we want to send a POST request to a server that accepts only text/json content type (instead of the usual application/json). In that case, we can customize the content type we want to send in the header:

const result = await axios.post('https://testapi.org/post', { name: 'John Doe' }, {
    headers: {
    'content-type': 'text/json'
    }
});

Alternatively, we can use variables instead of passing these objects directly into the axios.post() method. This definitely improves readability of our code:

const headers = {
    "Content-Type": "text/json"
};

const data = {
    name: "John Doe"
};

const result = await axios.post("https://testapi.org/post", data, {
    headers: headers
});

Let's just quickly confirm this works as expected:

console.log(result.data.headers['Content-Type']); // text/json

Conclusion

In this article, we learned how to send headers with POST requests in Axios, as well as the structure of an Axios request, so that we do not mistake the config object for the data object, as many people do.

Original article source at: https://stackabuse.com/

#javascript #axios #post #request 

Send Headers With an Axios POST Request
Gordon  Murray

Gordon Murray

1677075420

How to GET HTTP Request in React

How to GET HTTP Request in React

Introduction

When developing web applications - we routinelly access resources hosted on a server. Asking for, sending, or performing other operations on resources is accomplished through HTTP requests. These requests are sent from the client to a host on a server. When making HTTP request, the client employs a URL (Uniform Resource Locator) and a payload that contains the necessary information to access the server resources.

The five commonplace HTTP request methods are GET, PUT, POST, PATCH, and DELETE. These methods allow us to perform standard CRUD operations.

In this article, we will learn how to make a GET HTTP request in React using either Axios or the Fetch API, as well as how to do so in both class and functional components.

Note: In this article, we will use the JSON Placeholder Free Fake Posts REST API to perform a GET HTTP request on its server to retrieve some resources.

What is GET Request?

GET is an HTTP request method that is used to obtain resources from servers.

Axios and the Fetch API are the two main methods for making HTTP requests.

  • The Fetch API is a built-in promise-based JavaScript module for retrieving resources from a server or an API endpoint.
  • Axios is a promise-based HTTP client library that makes it simple to send asynchronous HTTP requests to REST endpoints. This is an external library that must be installed.

In this article, we'll look at how to perform GET requests in React functional components using the Fetch API and Axios methods, and then how to do the same in class-based components.

How To Perform GET HTTP Request in React's Functional Components

A functional component is created when a JavaScript function (either normal or ES6) returns a React element (JSX). We use React hooks when working with functional components, which are very important when performing GET requests.

We'll use the useState() and useEffect() hooks. Because the useEffect() hook renders immediately when the app mounts we always perform GET requests within it, and we use the useState() hook to store our data/response.

How To Perform GET HTTP Request in React's Functional Component with the Fetch API

The fetch() method accepts one mandatory argument - the URL to the resource we want to fetch, as well as an optional argument that indicates the request method. The default value for that optional argument is GET, so it is not necessary to set it when making a GET request.

Then Fetch API returns a Promise, so we can use the then() and catch() methods to handle success or failure:

import { useState, useEffect } from 'react';

const App = () => {
   const [posts, setPosts] = useState([]);

   useEffect(() => {
      fetch('https://jsonplaceholder.typicode.com/posts')
         .then((res) => res.json())
         .then((data) => {
            console.log(data);
            setPosts(data);
         })
         .catch((err) => {
            console.log(err.message);
         });
   }, []);

   return (
      // ... consume here
   );
};

This is what a standard GET request looks like. Now, let's decompose what we've done so far so that you gain a better understanding of the code above. First of all, we created a state to hold all the resources/posts we would fetch from the posts API:

const [posts, setPosts] = useState([]);

Then we made use of the useEffect() hook and wrote our GET request in it so that the request is triggered immediately after the app mounts:

useEffect(() => {
   fetch('https://jsonplaceholder.typicode.com/posts')
      .then((res) => res.json())
      .then((data) => {
         console.log(data);
         setPosts(data);
      })
      .catch((err) => {
         console.log(err.message);
      });
}, []);

After that, we created a fetch request in the useEffect() hook and passed the URL we can use to access the server. Since this returns a promise, we used the then() method. Because this method returns a response object rather than JSON, we first converted the data to JSON format:

useEffect(() => {
   fetch('https://jsonplaceholder.typicode.com/posts')
      .then((res) => res.json())
}, []);

Then we proceeded to get the posts/data and stored them in the state we created earlier:

useEffect(() => {
   fetch('https://jsonplaceholder.typicode.com/posts')
      .then((res) => res.json())
      .then((data) => {
         console.log(data);
         setPosts(data);
      }
}, []);

Finally we use the catch() method to handle errors:

useEffect(() => {
   fetch('https://jsonplaceholder.typicode.com/posts')
      .then((res) => res.json())
      .then((data) => {
         console.log(data);
         setPosts(data);
      })
      .catch((err) => {
         console.log(err.message);
      });
}, []);

We've already performed a GET request and saved our data to the state we created. Now we can consume the data within our React application.

How To Perform GET HTTP Request in React's Functional Component With Axios

Aside from the Fetch API, we can also use Axios to send GET requests. Axios is a promise-based HTTP client library that makes it simple to send asynchronous HTTP requests to REST endpoints.

If we want to use Axios, which is an external library, we must first install it in our project by running the following command in our project's directory:

$ npm install axios

Once we've successfully installed Axios, we can proceed to perform our GET request:

import { useState, useEffect } from 'react';
import axios from 'axios';

const App = () => {
   const [posts, setPosts] = useState([]);

   useEffect(() => {
      axios
         .get('https://jsonplaceholder.typicode.com/posts?_limit=10')
         .then((response) => {
            setPosts(response.data);
         })
         .catch((err) => {
            console.log(err);
         });
   }, []);

   return (
      // ...
   );
};

This looks a lot cleaner than that of Fetch API! Taking a look at the code above, we started by importing Axios since it was an external library we installed:

import axios from 'axios';

We then performed the GET request within the useEffect() hook as we did for Fetch API, but this time the syntax is a little different:

useEffect(() => {
   axios
      .get('https://jsonplaceholder.typicode.com/posts?_limit=10')
      .then((response) => {
         setPosts(response.data);
      })
      .catch((err) => {
         console.log(err);
      });
}, []);

In contrast to the Fetch API method, no options are required to declare the method. We simply attach the method to the instance and query it, also there is no need to convert the data because it returns it as JSON.

How To Perform GET HTTP Request in React's Class Component

A class component is an ES6 class that returns JSX and requires React extensions to be used. Before the introduction of hooks, this was the most commonly used method (i.e. earlier versions 16.8) because the state could not be used within functional components.

Despite the availability of hooks, many people continue to use class components. Let's look at how we can use the constructor() method's state property, and the ComponentDidMount() lifecycle method to perform GET HTTP requests in React with class components.

How To Perform GET HTTP Request in React's Class Components With Fetch API

This is very similar to how we performed the GET request in functional components. The only difference is that we will now use the state property in the constructor() method rather than the useState() hook. Also, we will handle our GET request in the ComponentDidMount() lifecycle rather than the useEffect() hook, so that this request is triggered once our app mounts:

import React, { Component } from 'react';

class App extends Component {
   constructor(props) {
      super(props);
      this.state = {
         posts: [],
      };
   }

   componentDidMount() {
      fetch('https://jsonplaceholder.typicode.com/posts')
         .then((response) => response.json())
         .then((data) => this.setState({ posts: data }))
         .catch((error) => console.log(error));
   }

   render() {
      const { posts } = this.state;

      return (
         // ... 
      );
   }
}

In the code above, we made use of the constructor method to initialize an object's state to store the resource/data we will get from our server/API:

constructor(props) {
   super(props);
   this.state = {
      posts: [],
   };
}

We then performed our GET request in the componentDidMount() lifecycle method so that it's triggered once the app mounts:

componentDidMount() {
   fetch('https://jsonplaceholder.typicode.com/posts')
      .then((response) => response.json())
      .then((data) => this.setState({ posts: data }))
      .catch((error) => console.log(error));
}

state is an object which holds many states, we first destructure it to get the posts state, which can later be used:

render() {
   const { posts } = this.state;

   return (
      // ... use here
   );
}

How To Perform GET HTTP Request in React's Class Components With Axios

As we saw with functional components, we can send GET requests with Axios. All that remains is to execute the GET request within the ComponentDidMount() lifecycle and to import Axios:

import React, { Component } from 'react';
import axios from 'axios';

class App extends Component {
   constructor(props) {
      super(props);
      this.state = {
         posts: [],
      };
   }

   componentDidMount() {
      axios
         .get('https://jsonplaceholder.typicode.com/posts')
         .then((response) => {
            this.setState({ posts: response.data });
         })
         .catch((error) => {
            console.log(error);
         });
   }

   render() {
      const { posts } = this.state;
      return (
         // ...
      );
   }
}

Conclusion

We learned how to perform GET HTTP requests with both functional and class components using the two most commonly used methods - the Fetch API and Axios, in this article.

Using a specific method is entirely up to you.

Original article source at: https://stackabuse.com/

#react #http #request 

How to GET HTTP Request in React

Write a Request For Proposal (RFP) that Drives Responses

As a marketer, you have a lot of things on your plate and can’t manage everything on your own. Moreover, some tasks are just not possible or practical to manage manually. At some point, you’re going to need to work with other businesses that offer tools or services to help you do your job more efficiently. That’s where a request for proposal comes in, enabling you to attract prospective vendors who can help you achieve your business goals.

If you’ve never written a request for proposal (RFP) before, you may not know how to get started or what you need to include. The good news is, we’re here to help. This guide walks you through the process of writing a successful request for proposal that drives responses from the most viable vendors. Let’s dive right in.

What is a Request for Proposal (RFP)?

A request for proposal or RFP is a document that provides a list of requirements that vendors need to meet to complete a project. Typically sent out by businesses that need to find the right technology solution or professional service, it serves as an open invitation for vendors to submit their proposals. This enables them to attract potential vendors who can provide them with the tools they need or to whom they can outsource some of their work.

It's crucial to get your request for proposal right because it details all the criteria that vendors must meet in order to win the bid. As such, it enables you to collect proposals from the most relevant vendors, making it easier to decide on the right one for your business. 


8 Steps to Writing a Request for Proposal

So, if a request for proposal is so important, how do you write one? Check out the steps below to start writing your very own request for proposal.

steps to writing a request for proposal

1: Define the project, scope, and budget

Start with a clear definition of what the project is and understand the role that the vendor will play in it. In other words, have a proper idea of what you need from the vendor before you can write your request for proposal. Discuss what you need the vendor to do, how it should be done, and how long it should ideally take to be completed. 

Additionally, you’d also need to talk about how much you’re willing to spend for the service or platform. This provides you with a solid foundation for your RFP as you clearly know what you’re looking for.  


2: Provide an introduction

Now that you have a clear idea of what you’re looking for, it’s time to write an introduction explaining your project and expectations. The introduction should be able to help potential vendors understand the purpose of your RFP and what they need to help you achieve. This would also be a good opportunity to explain if you’re facing any challenges and how the vendor can help you overcome them.

Besides these basics, you may also want to include additional information about your project. This may be details such as when you intend to start the project and how long it will run. The introduction should help potential vendors get a better idea of your needs so they can assess their ability to meet them.


3: Explain the history of your company and project

Next, it’s time to introduce your company to the vendors. Give them a brief history of your company and what you do as well as the project you’re undertaking. Talk about your brand values, history, and other important background information. This information should be able to help vendors understand your market and where your business currently stands. 

Keep in mind that many of the potential vendors may have never heard of your company before. Make it easy for them to make an informed decision by giving them a sense of who you are as a brand. They can then use this information to assess whether they’re the right fit for your needs and whether they’d want to work with you.


4: Describe your requirements

Now comes the most important part where you describe exactly what you need in a vendor. Provide specific details about the services or solutions that you’re looking for to help you achieve your goal. Be sure to include details such as the level of experience you’re looking for (in the case of service solutions). For software solutions, you may also want to include details such as the level of access you need based on your team size.

It’s important to get as specific as possible in this section so potential vendors can know if they’re offering the solution you need. This will help them decide if they should send in a proposal or not, allowing you to instantly filter your options to get proposals from the most suitable prospects.

For example, if you’re looking for a social media marketing agency, you may be in need of an agency that can take care of content planning, production, and scheduling. Additionally, you may even need them to manage your community on your behalf. In this case, an agency that doesn’t offer community management may opt to avoid sending in a bid, so you don’t need to waste your time reviewing their proposal.

Alternatively, let’s say you’re looking for a social media management tool for a team of three. And you want to be able to plan your content, schedule your posts, monitor your comments, and analyze results all in one place. That way, only those vendors who can meet the above requirements will send in a proposal for you to review so you’re instantly filtering your options.


5: Give submission instructions

Vendors who plan on sending in a proposal should know how to respond to your request for proposal. Make sure you’re providing clear instructions on the structure they should follow in their proposal as well as what they need to include. When all the proposals are formatted in a similar way, it becomes easier for you to process the information and evaluate them.

For example, you may require them to include a certain number of headings. Or you may even request them to provide a list of points under each heading. Additionally, you may also ask them to send in samples of their previous work, case studies, and demos to better evaluate their quality of work or platform capabilities. 


6: Include your selection criteria

It’s also important that you include a detailed list of the criteria using which you’ll be evaluating the proposals. This gives vendors an idea of how they’ll be evaluated so they can understand their chances of winning the bid. As such, only the most qualified vendors will respond to your request for proposal, making it easier for you to sort through your options.

Provide details about your priorities, basic requirements, and preferences so vendors know exactly what you’re looking for and how to position their offerings. For example, you may prioritize agencies that specialize in content production beyond their marketing services. The basic requirements could be the ability to plan and execute social media marketing campaigns, while you may prefer agencies that have experience working with companies in a certain industry.


7: Specify the RFP timeline

Additionally, it’s crucial for everyone involved to know your target timeline. When do you expect to receive the responses? When will the selected vendor be announced? Make sure to include these key deadlines so vendors don’t have to keep reaching out to you for updates when you haven’t made your selection.

Besides these, you’d also want to include your project start time and end time. Knowing these timelines will allow vendors to plan their schedules and assess their availability before they choose to respond. This benefits both parties because you don’t want to end up working with a vendor who’d eventually not be able to help you meet the deadline. Also, vendors will be able to understand whether they can fit your project in considering their current workload.

This is particularly important for RFPs that are seeking service solutions. Keep in mind that depending on how detailed your requirements are, you’ll need to adjust your timeline accordingly. If vendors have to provide a highly detailed proposal, they may require more time to plan their response. 


8: Proofread, revise, and go live

Now that you’ve written down all the crucial information, it’s time to proofread your request for proposal. Look for spelling mistakes and grammatical errors as well as complicated sentences that may be difficult to understand. You want to come across as professional and trustworthy while avoiding any chances of miscommunication.

Besides the basics, make sure you’re on the lookout for mistakes that could be detrimental to your project’s timeline. For instance, a typo in your deadline could result in you losing out on potential vendors because they couldn’t meet it or a huge delay in receiving your proposals. Alternatively, a missing 0 in your project budget could mean losing out on potential vendors who declined to bid because the pay was too low.

Make any necessary revisions and give the RFP a once-over to ensure that it’s professional and clear. You’ll then be able to finally go live with your request for proposal.

Best Practices to Write an Effective RFP

In addition to simply following the steps above, there’s a certain way to make sure that your RFP gets the responses it deserves. Follow these best practices to write an effective request for proposal.

best practices to write FRP

  • Keep It Simple and Easy to Understand

To avoid the chances of miscommunication, make sure you use language that’s understandable to your potential vendors. You may want to cut back on the industry jargon and resort to simple English while still keeping it professional. Try to avoid long run-on sentences and instead cut them to shorter, more bite-sized sentences that are easier to process.

  • Make the Most of Headings and Bullet Points

Headings and bullet points make your RFP easier to digest compared to large blocks of text. Make the most of them to break up your request for proposal and make it more scannable.

  • Be as Detailed as Possible

Don’t miss important details that could help potential vendors understand your project and requirements better. Vendors are more likely to respond with the right proposal when they have a clear idea of what you’re looking for and what kind of role they’ll play.


Example of a Request for Proposal

Still not sure what your request for proposal should look like? Let’s take a look at an example of how a typical RFP looks so you can get a better idea.

Request for Proposal: Social Media Services for June’s Vintage
16 December 2022
Issued by: June’s Vintage
Contact Person: June Phillips
j.phillips@junesvintage.com
(445)917-3069

Introduction

June’s Vintage, a retail store that deals in vintage clothing, is accepting proposals to find a reliable agency to manage our social media on our behalf. The purpose is to:

  • Grow our social media community.
  • Engage our audience on an ongoing basis.
  • Maintain a strong brand presence across leading social networks (Instagram, Facebook, and TikTok).

The objective of this request for proposal is to find a social media agency that will provide the best overall value and deliver impressive results. We’re hoping to run a test project for three months after which we may decide on a long-term partnership.

Background

Our vintage business was established in 2007 and has since established a strong customer base throughout Philadelphia. Most of our customers are local fashion enthusiasts roughly between the ages of 25 and 50 and shop in-store. However, as we expand to online shopping channels, there’s an opportunity to extend this reach beyond the local area. This has proved to be challenging as our social media presence is fairly limited and we lack the time and know-how to actively engage our audience on social media. 

Project Overview

We would like to be able to consistently post and engage with audiences across three key social media platforms–Instagram, Facebook, and TikTok. As such, we’re looking for an agency that can help us with the following:

  • Create a solid social media strategy complete with a publishing calendar.
  • Develop fresh content ideas and take care of content creation in accordance with the publishing calendar.
  • Schedule and publish posts on our behalf.
  • Monitor and respond to customer comments.
  • Run a week-long advertising campaign to attract new followers/customers.

Our budget is $2,500 per month with some room for flexibility depending on the level of service that can be provided. Ideally, we would like to employ an agency that has experience working with small retail stores and local businesses.

Submission Guidelines

All proposals must be created using the format below (bulleted lists will be highly appreciated):

  • Executive summary
  • Business background 
  • Highlight your unique selling point
  • Provide relevant experience that makes you qualified for the project
  • Details of proposed deliverables and services
  • Note the social media management tools you will use to complete the necessary tasks
  • Not how content will be shared with us for approval
  • Include your rates
  • References and/or case studies
  • Provide samples of social media content created for previous clients
  • Additional terms and conditions to work with your agency 

Please submit your proposal in .pdf format to j.phillips@junesvintage.com by January 30, 2023.

Evaluation Criteria

June’s Vintage will use the following criteria to evaluate proposals and select the right vendor:

  • Experience providing full-service social media solutions for a minimum of 24 months
  • Responsiveness to the requirements highlighted above
  • Competitiveness of service rates
  • Testimonials from past/current clients
  • Tools and technology used to carry out necessary tasks

Timeline

June’s Vintage expects to complete the RFP and project according to the following timeline:

  • Issuance of request for proposal – December 16, 2022
  • Deadline to submit proposals – January 30, 2023
  • Vendor selection date – February 15, 2023
  • Finalization of contract and other project discussions – February 20, 2023
  • Project start date – March 1, 2023
  • Initial project completion – May 31, 2023

Getting Started with Your First Request for Proposal

Now that you know exactly what a request for proposal looks like and what to include in it, it’s time to write your very own. There are plenty of free templates available online that can help you draft the perfect request for proposal. 

Original article source at: https://influencermarketinghub.com/

#write #request #example 

Write a Request For Proposal (RFP) that Drives Responses
Nigel  Uys

Nigel Uys

1671263940

Send GET and POST AJAX request with JavaScript

AJAX is the only way that allows communicating client-side with the server side.

It is easier to send AJAX requests using JavaScript libraries or frameworks. But it is also good to know how to send AJAX request with plain Javascript.

Use the XMLHttpRequest object to communicate with the server.

In this tutorial, I show how you can send GET and POST AJAX requests with JavaScript and handle the request with PHP.

Contents

  1. Create a Table
  2. Database Configuration
  3. Create HTML layout
  4. Create a PHP file to handle AJAX request
  5. How to make an AJAX request with JavaScript
  6. Output
  7. Conclusion

1. Create a Table

Create employee table and added some records.

CREATE TABLE `employee` (
  `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
  `emp_name` varchar(80) NOT NULL, 
  `salary` varchar(20) NOT NULL,
  `email` varchar(80) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

2. Database Configuration

Create a config.php for the database connection.

Completed Code

<?php

$host = "localhost"; /* Host name */
$user = "root"; /* User */
$password = ""; /* Password */
$dbname = "tutorial"; /* Database name */

$con = mysqli_connect($host, $user, $password,$dbname);
// Check connection
if (!$con) {
  die("Connection failed: " . mysqli_connect_error());
}

3. Create HTML layout

Create 3 input text elements for entering the name, salary, and email. And a button element.

Added onclick event on the button which calls insertNewEmployee() function.

List records in the <table id='emptTable'> using JavaScript and AJAX.

Completed Code

<div>
   Name: <input type="text" id='txt_name'> <br>
   Salary: <input type="text" id='txt_salary'> <br>
   Email: <input type="text" id='txt_email'> <br>
   <input type="button" id="btn_submit" value="Submit" onclick="insertNewEmployee();">
</div>
<table id='empTable' border='1'>
  <thead>
    <tr>
      <th>Name</th>
      <th>Salary</th>
      <th>Email</th>
    </tr>
  </thead>
  <tbody></tbody>
</table>

4. Create a PHP file to handle AJAX request

Create 'ajaxfile.php' file to handle AJAX request.

For example purpose, I am handling both GET and POST requests in a single file.

Assigned 2 to $request.

GET request (fetch records)

Check if $_GET['request'] is set or not if set then assign $_GET['request'] to $request.

If $request == 1 then fetch all records from employee table and assign to $employeeData. Loop on the fetched records.

Initialize $response with id, emp_name, salary, and email keys.

Return $response Array in JSON format.

POST request (insert record)

If $request == 2 then read POST values using json_decode(file_get_contents("php://input")).

Assign values to variables and prepare INSERT query.

If the INSERT query is executed successfully then return 1 otherwise 0.

Completed Code

<?php

include "config.php";

$request = 2;

// Read $_GET value
if(isset($_GET['request'])){
   $request = $_GET['request'];
}

// Fetch records 
if($request == 1){

   // Select record 
   $sql = "SELECT * FROM employee";
   $employeeData = mysqli_query($con,$sql);

   $response = array();
   while($row = mysqli_fetch_assoc($employeeData)){
      $response[] = array(
         "id" => $row['id'],
         "emp_name" => $row['emp_name'],
         "salary" => $row['salary'],
         "email" => $row['email'],
      );
   }

   echo json_encode($response);
   exit;
}

// Insert record
if($request == 2){

   // Read POST data
   $data = json_decode(file_get_contents("php://input"));

   $name = $data->name;
   $salary = $data->salary;
   $email = $data->email;

   // Insert record
   $sql = "insert into employee(emp_name,salary,email) values('".$name."',".$salary.",'".$email."')";
   if(mysqli_query($con,$sql)){
      echo 1; 
   }else{
      echo 0;
   }

   exit;
}

5. How to make an AJAX request with JavaScript

Use XMLHttpRequest object to send AJAX request.

.open() – Methods takes 3 parameters –

  1. Request method – GET or POST.
  2. AJAX file path. Pass parameter with URL on GET request – ajaxfile.php?name=yogesh&city=bhopal.
  3. It is an optional parameter that takes Boolean value true or false. Default value is true. Pass true for asynchronous and false for synchronous request.

.setRequestHeader() – This method is used to set Content-Type. By default, 'application/x-www-form-urlencoded' content-type is set. You can change its value e.g. – application/jsonmultipart/form-data, etc.

.onreadystatechange – This property calls on request state change. Assign an anonymous function to process the response. If this.readyState == 4 && this.status == 200 means the server response is ready for processing.

.send() – This method send AJAX request. It is also used to send data.


AJAX GET request JavaScript

  • Syntax –
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "ajaxfile.php?request=1", true);
xhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhttp.onreadystatechange = function() {
   if (this.readyState == 4 && this.status == 200) {

      // Response
      var response = this.responseText; 

   }
};
xhttp.send();

Above syntax with jQuery

$.ajax({
  url: 'ajaxfile.php?request=1',
  type: 'get',
  success: function(response){

  }
});

AJAX POST request JavaScript

  • Syntax –

application/x-www-form-urlencoded; charset=UTF-8 is a default Content-Type but you can use any other type e.g. – application/jsonmultipart/form-data, etc.

var xhttp = new XMLHttpRequest();
xhttp.open("POST", "ajaxfile.php", true); 
xhttp.setRequestHeader("Content-Type", "application/json");
xhttp.onreadystatechange = function() {
   if (this.readyState == 4 && this.status == 200) {
     // Response
     var response = this.responseText;
   }
};
var data = {name:'yogesh',salary: 35000,email: 'yogesh@makitweb.com'};
xhttp.send(JSON.stringify(data));

Above syntax with jQuery

$.ajax({
   url: 'ajaxfile.php',
   type: 'post',
   data: {name:'yogesh',salary: 35000,email: 'yogesh@makitweb.com'},
   success: function(response){

   }
});

Create 2 functions –

  • loadEmployees() – This function calls on page successfully loaded.

Create object of XMLHttpRequest. Specify GET request and AJAX file path with parameter ('ajaxfile.php?request=1') in .open() method. Set Content-type and handle server response with onreadystatechange property.

Parse the this.responseText to JSON object and select <table id='empTable'> <tbody> and empty it.

Loop on the response to read values. Create a new table row element and assign a response value in cell.

Send the request by calling send() method.

  • insertNewEmployee() – This function calls on Submit button click.

Read values from the textboxes and assign them in variables. If variables are not empty then create a data JSON object. Initialize data object with the textbox values.

Create XMLHttpRequest object and specify POST request and AJAX file path ('ajaxfile.php') in .open() method. Set Content-type to 'application/json' and handle server response with onreadystatechange property.

Assign this.responseText in response. If response == 1 then alert a message and call loadEmployees() function to fetch records.

Completed Code

loadEmployees();

// Send AJAX GET request with JavaScript
function loadEmployees() {
   var xhttp = new XMLHttpRequest();

   // Set GET method and ajax file path with parameter
   xhttp.open("GET", "ajaxfile.php?request=1", true);

   // Content-type
   xhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');

   // call on request changes state
   xhttp.onreadystatechange = function() {
      if (this.readyState == 4 && this.status == 200) {

       // Parse this.responseText to JSON object
       var response = JSON.parse(this.responseText);

       // Select <table id='empTable'> <tbody>
       var empTable = 
document.getElementById("empTable").getElementsByTagName("tbody")[0];

       // Empty the table <tbody>
       empTable.innerHTML = "";

       // Loop on response object
       for (var key in response) {
          if (response.hasOwnProperty(key)) {
             var val = response[key];

             // insert new row
             var NewRow = empTable.insertRow(0); 
             var name_cell = NewRow.insertCell(0); 
             var username_cell = NewRow.insertCell(1); 
             var email_cell = NewRow.insertCell(2);

             name_cell.innerHTML = val['emp_name']; 
             username_cell.innerHTML = val['salary']; 
             email_cell.innerHTML = val['email']; 

          }
       } 

      }
   };

   // Send request
   xhttp.send();
}

// Send AJAX POST request with JavaScript (Insert new record)
function insertNewEmployee() {

  var name = document.getElementById('txt_name').value;
  var salary = document.getElementById('txt_salary').value;
  var email = document.getElementById('txt_email').value;

  if(name != '' && salary !='' && email != ''){

     var data = {name: name,salary: salary,email: email};
     var xhttp = new XMLHttpRequest();
     // Set POST method and ajax file path
     xhttp.open("POST", "ajaxfile.php", true);

     // call on request changes state
     xhttp.onreadystatechange = function() {
       if (this.readyState == 4 && this.status == 200) {

         var response = this.responseText;
         if(response == 1){
            alert("Insert successfully.");

            loadEmployees();
         }
       }
     };

     // Content-type
     xhttp.setRequestHeader("Content-Type", "application/json");

     // Send request with data
     xhttp.send(JSON.stringify(data));
  }

}

6. Output

View Output


7. Conclusion

With the use of XMLHttpRequest object send AJAX GET and POST requests.

In GET request directly pass data with a filename like – ajaxfile.php?name=yogesh&city=bhopal and in POST request pass your data in send() method.

If you found this tutorial helpful then don't forget to share.
 

Original article source at: https://makitweb.com/

#javascript #ajax #request 

Send GET and POST AJAX request with JavaScript

Learn PUT and PATCH Request in API

Introduction

  • APIs employs various HTTP methods but PUT, and PATCH are likely the two that cause the most confusion.
  • The resources can be updated or modified using either one of them.

Let's discuss how these approaches differ from one another.

PUT

The PUT method offers a technique to edit resources by delivering data that updates the entire resource.

PUT will completely swap out a resource if it already exists and creates the resource if it doesn't exist.

Imagine you wish to update the user using an API. We transmit all of the resource's attributes along with the PUT request.

PUT API request consumes more bandwidth than PATCH because we send all of the resource's contents using it.

PUT Request payload{
    "email":"xyz@zzz.com",
    "firstname":"qwerty",
    "lastname":"test",
    "pipeline_url":"https://test.com/pipeline"
}

PATCH

  • It's an alternate technique for upgrading resources.
  • In this instance, the client provides a portion of the modified data rather than changing the complete resource.
  • Fields that are not part of the payload won't be updated.

We're sending an email and a pipeline_url.

PATCH Request payload{
    "email":"xyz@zzz.com",
    "pipeline_url":"https://test.com/pipeline"
}

PATCH consumes less bandwidth than PUT because we only send information that needs to be updated.

Original article source at: https://www.c-sharpcorner.com/

#put #request #api #http 

Learn PUT and PATCH Request in API
Leonard  Paucek

Leonard Paucek

1667036640

Codeigniterplus: The Ultimate Codeigniter Enhancements

Codeigniterplus

Codeigniterplus is scaffolding for a good standard web application, built on the top of codeigniter framework and extended with various other third party frontend/backend libraries/techonlogies. This will help developers to have a kick-ass quick start along their way to better managed web application development.

Technical Requirement

  • PHP version 5.3.x
  • Mysql version 5.x+ Database Engine(Should work with other db as well which doctrine support. But I haven't tested yet)
  • Composer (to install and use third party libraries through it, which is highly recommended).
  • Bower to install front-end any third party packages.

Basic Site functionality

  • Set up with modern dependency based PHP development standard.
  • Set up with modern front end development stack(bower, bootstrap, jQuery).
  • You will get ready made authentication functionality
  • An organized integrated view template structure so that you don't get lost in a sea of view files.
  • Separate view root for front-end/public pages and back-end/authenticated users' pages.
  • Basic Administration panel, to perform administration functionality. You have your freedom to add as much as you want :).
  • Integrated basic SEO settings, seo for pagination.

See all available feature in details also.

*nix Installation

  • Change application/config/database.php according to your database server credential and commit locally(or add that file to .gitignore file).
  • Create a makefile as instructed on deployment wiki page.
  • run the 'make all' command.

Windows Installation

This project is tightly coupled with composer and bower. So, make sure you have them installed and you know the basics!

  • Crate a new project with your chosen name.
  • Paste all file from CodeIgniterPlus to your project directory.
  • Run "composer update" command to get doctrine dependency installed.
  • Run "bower install" command to get latest front-end packages installed.
  • Change 'RewriteBase' on '.htaccess' file as per your your chosen name. If using root level domain, just remove it and keep as 'RewriteBase /'.
  • Create a database with your given database name in config/database.php file.
  • Now edit config/database.php file; Here change the database server, database name, user name and password as per your database server.
  • Make sure the following directories exists(create if not) and do have write permission by the application(easy to have them with '777' mode):
    • {root}/application/cache
    • {root}/application/logs
    • {root}/application/models/proxies
  • Run http://{domain_path}/home/db_schema for create database tables from the doctrine entities, automatically. (Note :Every time when you update your entity file in models/entity directory just Run the above url for update existing schema.)
  • run the application, register with username 'admin'. This will cause to create default two roles 'admin' and user automatically and will make user 'admin' in 'admin' role. From this on, whenever a registration happens, all will be assigned default 'user' role. (Note: If you wish to change this functionality please do so on 'application/libraries/DX_Auth.php', starting at line 930.)

HomePage Screenshot:

Codeigniterplus Home Screen

References:

And introductory post to codeigniterplus: Introduction To CodeIgniterplus

Future Considerations:

  • Docker Integration(in progress!)
  • Front End enhancements: integrate requirejs, angularjs, grunt.
  • Unit Tests: add necessary PHPUnit tests for custom classes.
  • Acceptance/Functional Test: Using Codeception.
  • Support for other view engine: Current view engine logic already seperated to MY_Controller class. Additional logic should be integrated to generalize view engine choice, so that developers can use other engines they like, such as twig

Your Contribution

You can choose from the above 'Future considerations' section as well. In that case, you can optionally create a issue mentioning which feature you want to work on. Then, fork the repo, implement the feature/make changes and create a pull request. Thanks!

See Release Notes

See The Complete List Of Libraries Used For This Project

View Live Demo


.gitignore

/application/cache/
/application/logs/
/application/models/proxies/
/nbproject/
/vendor/
/bower_components/
/deploy.php
/makefile

.htaccess

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /codeigniterplus/

    #Removes access to the system folder by users.
    #Additionally this will allow you to create a System.php controller,
    #previously this would not have been possible.
    #'system' can be replaced if you have renamed your system folder.
    RewriteCond %{REQUEST_URI} ^system.*
    RewriteRule ^(.*)$ /index.php?/$1 [L]
    
    #When your application folder isn't in the system folder
    #This snippet prevents user access to the application folder
    #Submitted by: Fabdrol
    #Rename 'application' to your applications folder name.
    RewriteCond %{REQUEST_URI} ^application.*
    RewriteRule ^(.*)$ /index.php?/$1 [L]

    #Checks to see if the user is attempting to access a valid file,
    #such as an image or css document, if this isn't true it sends the
    #request to index.php
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ index.php?/$1 [L]
</IfModule>

<IfModule !mod_rewrite.c>
    # If we don't have mod_rewrite installed, all 404's
    # can be sent to index.php, and everything works as normal.
    # Submitted by: ElliotHaughin

    ErrorDocument 404 /index.php
</IfModule>

.travis.yml

## YAML Template.
---
language: php
php:
  - 5.5

before_script:
  - composer self-update
  - composer update

Download Details:

Author: ranacseruet
Source Code: https://github.com/ranacseruet/codeigniterplus

License: View license

#codeigniter 

Codeigniterplus: The Ultimate Codeigniter Enhancements
Jane  Reid

Jane Reid

1666948200

Sprint PHP: A Lightweight, Modern Addition to CodeIgniter 3

Sprint PHP

NOTE: This repo is no longer being maintained. If you would like to take it over please email me at lonnieje@gmail.com.

Based on the CodeIgniter 3 PHP framework, Sprint provides the essential running start to get you to the fun part of building your web applications. It provides additional utilities and workflow enhancements to stock CodeIgniter. In the process, it helps to modernize the code a bit.

Sprint is intended to be the heart of Bonfire Next, though that integration has not happened yet.

Why Sprint?

I found that for a number of my recent projects, the current Bonfire code was too much, too opinionated and fully developed. And the clients were requesting for me to use the Foundation CSS Framework since that's what they use in house, and Bonfire was built on Bootstrap. Besides, sometimes Bonfire is just too big of an application for your projects.

While working on Bonfire Next and an in-progress book on modernizing CodeIgniter and it's practical usage, I realized that I could reform the current slimmer codebase that I've been using and make it the core of Bonfire Next. The goal is to have basic functionality and workflow in place in Sprint, and to build on that in Bonfire.

So Sprint is basically CodeIgniter, but with more cowbell.

NOTE: This is currently in a Beta-release state. What's that mean? It means that no new features are expected, but is a time for bugs to get hunted down and stomped out. If you use the project and find changes to the code or docs, pull requests are accepted :) Preferably with tests in place, though I won't be enforcing that at this point.

System Requirements

  • PHP version 5.4 or newer.
  • SimpleXML enabled on your PHP installation for the docs to work.
  • Composer installed on development server.
  • A Database. We currently use MySQL but try to keep it fairly flexible.

Found A Security Issue?

I take security very seriously in Sprint and strive to create the most secure package that I can. If you have located what you believe to be security issues, please contact me at lonnie@newmythmedia.com with the details, instead of posting them as an issue on the repo or forums. That only releases the security hole to potential attackers before it's had a chance to be fixed.

How To Install?

Installation instructions can be found in the docs source here on GitHub.

What's In The Box?

The following is being built for the initial release:

  • Powerful MY_Model with standard CRUD, db wrappers, observer methods and in-model validation
  • MY_Controller with simple theming, rendering methods for other data types (like json) and more
  • Extended Router to include module support, named routes, HTTP verb-based routing, Restful resources and scoped routes/areas.
  • Simple, but flexible, Template system
  • Module Support, without being able to call other controllers. That simply gets too complex and causes too many problems. Instead, it's simply the ability to keep MVC triads in modules that can still be called from the URI.
  • Better Database Migrations, with CLI tool for building and running
  • Database Seeding with CLI tool
  • Markdown-based documentation system.
  • Flexible Events system with priotized publish/subscribe methodology.
  • Simple, GUI-less cron controller that can be used through standard crontab or scheduled tasks.
  • Settings library for maintaining system-wide settings, either in the database, config files, or a combination.
  • Simple, but expandable, Authentication and Authorization system with flexible Password strength checking
  • Email Queue system allows for very flexible email generations and sending.
  • The Forge - a code builder with simple generators in place, but fully customizable and easy to add your own.

What's NOT included?

Sprint will not include much in the way of a built-in admin area, though it will have default views that can be incorporated into your own areas.

It will not include a method for working with assets as much of this can be handled easier and with higher performance on a per-project basis, often using something like CodeKit.

Where's the Docs?

Docs are included in the repo itself, and it comes with a pretty nice documentation system built on simple Markdown-formatted files.

To view the documentation, download the code, and point your browser to /docs. The rest should be working fine, but please let me know if you hit any snags!

To view the docs prior to downloading, you'll have to browse the files in the repo for now. Before too long, we'll have a site setup for it. But the current focus is on the initial release getting whipped into shape.


.gitattributes

# Lists files and folders that should NOT be included
# in archives made by git. Mostly used when pulling
# the project in through Composer and using --prefer-dist

.travis.yml
.gitattributes
readme.md

tests/unit/myth/
tests/acceptance/myth/
tests/functional/myth/

.gitignore

# Mac Stuff
.DS_Store

# IDE Files
.idea/*
*.sublime-workspace
*.sublime-project

# Development Settings
application/config/development/*

# Composer Installs
vendor/*

oldstuff/*
application/logs/*
application/cache/*
tests/_output/*
o
application/controllers/Test.php
application/views/test/baytwo.php
application/views/test/index.php

.htaccess

# ----------------------------------------------------------------------
# Start rewrite engine
# ----------------------------------------------------------------------

# Turning on the rewrite engine is necessary for the following rules and features.
# FollowSymLinks must be enabled for this to work.

<IfModule mod_rewrite.c>
  Options +FollowSymlinks -Indexes
  RewriteEngine On

  # If you installed this in a subfolder, you will need to
  # change the following line to match the subfolder you need.
  # http://httpd.apache.org/docs/current/mod/mod_rewrite.html#rewritebase
  RewriteBase /

  # Removes access to the system folder by users.
  # Additionally this will allow you to create a System.php controller,
  # previously this would not have been possible.
  # 'system' can be replaced if you have renamed your system folder.
  RewriteCond %{REQUEST_URI} ^system.*
  RewriteRule ^(.*)$ /index.php?/$1 [L]
</IfModule>

# Rewrite "www.example.com -> example.com"

<IfModule mod_rewrite.c>
  RewriteCond %{HTTPS} !=on
  RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
  RewriteRule ^ http://%1%{REQUEST_URI} [R=301,L]
</IfModule>


#Checks to see if the user is attempting to access a valid file,
#such as an image or css document, if this isn't true it sends the
#request to index.php

<IfModule mod_rewrite.c>
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ index.php?/$1 [L]
</IfModule>

# Block access to "hidden" directories whose names begin with a period. This
# includes directories used by version control systems such as Subversion or Git.
<IfModule mod_rewrite.c>
  RewriteCond %{SCRIPT_FILENAME} -d
  RewriteCond %{SCRIPT_FILENAME} -f
  RewriteRule "(^|/)\." - [F]
</IfModule>

# If we don't have mod_rewrite installed, all 404's
# can be sent to index.php, and everything works as normal.
<IfModule !mod_rewrite.c>
    ErrorDocument 404 index.php
</IfModule>

# ----------------------------------------------------------------------
# UTF-8 encoding
# ----------------------------------------------------------------------

# Use UTF-8 encoding for anything served text/plain or text/html
AddDefaultCharset utf-8

# Force UTF-8 for a number of file formats
AddCharset utf-8 .css .js .xml .json .rss .atom

.travis.yml

language: php

php:
  - 5.4
  - 5.5
  - 5.6
  - hhvm

services: mysql

env: TRAVIS=1

matrix:
  allow_failures:
    - php: hhvm
  fast-finish: true

before_script:
  # Get Composer Up and Running
  - travis_retry composer self-update
  - travis_retry composer install --prefer-source --no-interaction --dev
  - travis_retry composer dump-autoload -o
  # Create the database and set a different root password
  - mysql -e 'create database IF NOT EXISTS sprint;' -uroot
  - echo "USE mysql;\nUPDATE user SET password=PASSWORD('root') WHERE user='root';\nFLUSH PRIVILEGES;\n" | mysql -u root
  # Get APACHE setup and running
#  - sudo apt-get install apache2 libapache2-mod-fastcgi
#  # enable php-fpm
#  - sudo cp ~/.phpenv/versions/$(phpenv version-name)/etc/php-fpm.conf.default ~/.phpenv/versions/$(phpenv version-name)/etc/php-fpm.conf
#  - sudo a2enmod rewrite actions fastcgi alias
#  - echo "cgi.fix_pathinfo = 1" >> ~/.phpenv/versions/$(phpenv version-name)/etc/php.ini
#  - ~/.phpenv/versions/$(phpenv version-name)/sbin/php-fpm
#  # configure apache virtual hosts
#  - sudo cp -f build/travis-ci-apache /etc/apache2/sites-available/default
#  - sudo sed -e "s?%TRAVIS_BUILD_DIR%?$(pwd)?g" --in-place /etc/apache2/sites-available/default
#  - sudo service apache2 restart

script:
  - php index.php database quietMigrate
  - php codecept.phar run unit --env travis

after_failure:
  - cat tests/_output/*

Download Details:

Author: ci-bonfire
Source Code: https://github.com/ci-bonfire/Sprint

#codeigniter #php 

Sprint PHP: A Lightweight, Modern Addition to CodeIgniter 3