What is the method for sending an array in x-www-form-urlencoded format using react-native?

this function is used for sending the API request

export const socialPostMurmur= (publicKey,content,sig,visibility,video,photo)=>{
  // console.log(publicKey,content,sig,visibility,video,photo);

  console.log('photo',photo);

let data;

  data="pub=" + publicKey.toString() +
  "&content=" + content +
  "&sig=" + sig.sig +
  "&visibility=" + visibility +
  "&videos=[]" +
  "&photos=" + photo

  console.log("data====",data)


  fetch('https://murmurjapi.wandx.co/accounts/postMurmur', {
method: 'POST',
headers: new Headers({
  "Content-Type": "application/x-www-form-urlencoded", // <-- Specifying the Content-Type
  Accept: "application/json"
}),
body:data
}).then((response) => response.json())
.then((responseJson) => {
  console.log("New post is called",responseJson);
  // return responseJson.movies;
})
.catch((error) => {
console.error('this is error',error);
});
}

the arguments `photo` and `video` in the function are expected to be arrays. When I log `photo`, it correctly displays an array like this:

["QmYTLjw3dzwNVzhMZGVdbZwbt7KTfc51exCWXeTKsy2bff-image-jpg-general"]

however, when the data is sent to the API and printed out, it does not show as an array. The response from the API call shows a status of failed with no error message.

This is how the array is formatted in the API request:

photos=QmYTLjw3dzwNVzhMZGVdbZwbt7KTfc51exCWXeTKsy2bff-image-jpg-general

this is the data that is being sent to the API

console.log("data====",data)

pub=EOS7qoTnhdcdihvcvEBkqNJ21iNwFJURRvgciHCuG2ihsvPZyPdL4&content=H&sig=SIG_K1_JwaNudk7P6AeogY9LSKey7hTwSTYM9E1GsLF3twRgqap6zCFVY78PzZgF1yA6GUTdDuC4vNXo1vUgwFCFKHppsyHc1zGVb&visibility=1&videos=[]&photos=QmYTLjw3dzwNVzhMZGVdbZwbt7KTfc51exCWXeTKsy2bff-image-jpg-general

this is the response received after the API call

New post is called 
{status: false, err: {…}}
status: false
err: {}
__proto__: Object

Answer №1

When it comes to encoding an array in the

application/x-www-form-urlencoded
, there is no one-size-fits-all approach. A common method, supported by PHP and body-parser in extended mode, is to add [] to the end of the name and repeat this for each value in the array.

For example:

const animals = ["dog", "cat", "mouse"];
const field_name = "animal[]";
const url_encoded_animals = animals.map(
    value =>
        `${encodeURIComponent(field_name)}=${encodeURIComponent(value)}`
);
const form_encoded = url_encoded_animals.join("&");
console.log(form_encoded);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Analyzing files that start with a period "."

I've come across a basic nodeJS script that reads files from a specific PATH and determines whether they are directories or not: var fs = require("fs"); var allFiles = fs.readdirSync(__dirname + '/bb'); allFiles.forEach(function(name){ if ...

Is there a way to include optional object properties in the entityAdapter.getInitialState() method?

After setting up the entityAdapter and selectors, I defined the initial state as follows: export const devicesAdapter = createEntityAdapter<Device>({ }) export const initialDevicesState = devicesAdapter.getInitialState({ listLoading: false, acti ...

Error encountered while compiling ./node_modules/@material-ui/core/ButtonBase/ButtonBase.js

I've encountered a frustrating error message: Failed to compile ./node_modules/@material-ui/core/ButtonBase/ButtonBase.js Module not found: Can't resolve '@babel/runtime/helpers/builtin/assertThisInitialized' in 'E:\IT&bsol ...

Is there a way to retrieve the field names from a JSON array within a for loop?

Here is the structure of my Json array: var data = { "categories": { "category1": { "Name": "Maps", "Id": 3, "orderInList": 1 }, "category2": { "Name": "B ...

npm ERROR! 404 Content removed by unidentified source on August 8, 2022 at 09:20:35.527 UTC

Upon running the command <npm view e-biz-znnf versions --json> in the terminal, npm throws an error message: npm ERR! code E404 npm ERR! 404 Unpublished by undefined on 2022-08-08T09:20:35.527Z npm ERR! 404 npm ERR! 404 'e-biz-znnf' is no ...

What's the best way to pair a number with a neighboring letter?

const userInput = "2a smith road"; const secondInput = "333 flathead lake road, apartment 3b" const formattedAddress = userInput.replace(/(^\w{1})|(\s+\w{1})/g, letter => letter.toUpperCase()); The final result will ...

Trouble arises when attempting to showcase document fields in MongoDB

As a beginner in programming, I am putting in my best effort to figure things out on my own. However, I seem to be stuck without any guidance. I am attempting to display all products from the mongoDB based on their brand. While I have successfully set up a ...

Experimenting with a function that initiates the downloading of a file using jest

I'm currently trying to test a function using the JEST library (I also have enzyme in my project), but I've hit a wall. To summarize, this function is used to export data that has been prepared beforehand. I manipulate some data and then pass it ...

How can you rearrange the order of objects in an array to only include duplicates?

https://i.sstatic.net/XwCDZ.png I don't want to alter the original order of objects in an array. However, I do need to retrieve items in a specific sequence when both the location and place are identical. I attempted a solution but it requires an ad ...

`How can I troubleshoot path obstacles when transferring files in node.js?`

I am having trouble moving a file from an HTML form to another folder using a cloud function. I am new to both node.js and firebase, so I am unsure of what I am doing wrong. This is my current code snippet: const fileMiddleware = require('express-mult ...

Implementing an automatic link generation feature for files within a directory using JavaScript

I could really use some assistance with this. I created a YouTube example, which can be viewed in this PLNKR LINK: http://plnkr.co/edit/44EQKSjP3Gl566wczKL6?p=preview In my folder named embed, I have files titled p9zdCra9gCE and QrMOu4GU3uU, as shown belo ...

Is it possible to programmatically click a plotly mode bar button using JavaScript in a Shiny app?

After some research, I've discovered that in order to achieve my goal, I need to incorporate shinyjs and extendShinyjs. Here's what I have implemented so far: In the ui.R file, outside of the ui function: js_reset_axes <- "shinyjs.reset_axes ...

Kendo UI Web - MultiSelect: choosing an option multiple times

Currently, I am encountering an issue with the Kendo UI MultiSelect widget when trying to select an option multiple times. An example of this is shown in the image below where I want to choose Schindler's List again after selecting The Dark Knight. Ho ...

Is it an issue: When using the shuffle() function in PHP, is it expecting an array as parameter 1, but instead,

I currently have an object that has been designed to follow the ArrayableInterface, specifically coming from Laravel's Eloquent ORM. The object in question is named $articles. Consequently, I am able to utilize it in the following manner: foreach ($ ...

Tips for integrating AsyncGenerators with Kotlin/JS

I am currently exploring the use of IPFS with Kotlin/JS, but my issue is not limited to that specific context. The functions ipfs.cat() and ipfs.get() return an AsyncGenerator, and I am uncertain about how to properly iterate over it using Kotlin (I am als ...

What is the best way to calculate the variance between the most recent and previous data points in an array in the span of an hour using JavaScript

Here is an array of objects I am working with: 0: {time: '2021-12-02T23:53:54.062Z', value: 558316} 1: {time: '2021-12-03T00:53:53.959Z', value: 558452} 2: {time: '2021-12-03T01:53:53.934Z', value: 558588} 3: {time: '2021 ...

javascript show and hide navigation bar

I am currently working on a HTML menu that includes a button to open it and an unordered list : <nav class="menu"> <button> <h1>Menu</h1> </button> <ul class="mylist" ...

Issue - The command 'bower install' terminated with Exit Status 1

During my journey through the angular-phonecat tutorial, a frustrating error popped up right after I executed the npm install command: I even checked the log file, but it just echoed the same error message displayed in the console. What's the piece o ...

The proper formatting of JSON strings in AWS using GraphQL

I'm currently working on creating an object value to be passed into DynamoDB using AWS AppSync and GraphQL. I'm almost there, but I'm facing challenges with nested JSON structures. Let's imagine I have an array: let officers = [{" ...

Ways to update a single column in an HTML table when there is a change

I'm stuck trying to find a more efficient method for updating a column in an html table without having to reload the entire table. The table consists of player stats, all pulled from my MYSQL database and displayed in the table except for the last col ...