发布来自React Native的x-www-form-urlencoded请求

tex*_*697 62 javascript http-post react-native fetch-api

我有一些参数,我想将表格编码POST到我的服务器:

{
    'userName': 'test@gmail.com',
    'password': 'Password!',
    'grant_type': 'password'
}
Run Code Online (Sandbox Code Playgroud)

我正在发送我的请求(目前没有参数)

var obj = {
  method: 'POST',
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
  },
};
fetch('https://example.com/login', obj)
  .then(function(res) {
    // Do stuff with result
  }); 
Run Code Online (Sandbox Code Playgroud)

如何在请求中包含表单编码的参数?

小智 190

您必须自己组合x-www-form-urlencoded有效负载,如下所示:

var details = {
    'userName': 'test@gmail.com',
    'password': 'Password!',
    'grant_type': 'password'
};

var formBody = [];
for (var property in details) {
  var encodedKey = encodeURIComponent(property);
  var encodedValue = encodeURIComponent(details[property]);
  formBody.push(encodedKey + "=" + encodedValue);
}
formBody = formBody.join("&");

fetch('https://example.com/login', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
  },
  body: formBody
})
Run Code Online (Sandbox Code Playgroud)

请注意,如果fetch在(足够现代的)浏览器中使用而不是React Native,则可以改为创建一个URLSearchParams对象并将其用作正文,因为Fetch Standard声明如果它body是一个URLSearchParams对象,那么它应该被序列化为application/x-www-form-urlencoded.但是,您无法在React Native中执行此操作,因为React Native 未实现URLSearchParams.

  • ES6方式:`const formBody = Object.keys(details).map(key => encodeURIComponent(key)+'='+ encodeURIComponent(details [key])).join('&');` (41认同)
  • 另一种类似的方式:`const formBody = Object.entries(details).map(([key,value])=> encodeURIComponent(key)+'='+ encodeURIComponent(value)).join('&')` (5认同)
  • URLSearchParams https://github.com/WebReflection/url-search-params 的这个 polyfill 可能适用于 React Native 或更旧的浏览器。 (2认同)
  • 它将json数组参数转换为字符串 (2认同)

Nic*_*ste 25

使用 URLSearchParams

https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams

var data = new URLSearchParams();
data.append('userName', 'test@gmail.com');
data.append('password', 'Password');
data.append('grant_type', 'password');
Run Code Online (Sandbox Code Playgroud)

  • -1; React Native中不存在`URLSearchParams`.(参见https://github.com/facebook/react-native/issues/9596.) (5认同)
  • 它现在是 React Native 的一部分。在传递它请求“body”之前,一定要在数据上调用“toString()”。 (5认同)

小智 18

您可以使用 UrlSearchParams 然后执行 toString() ,如下所示:

这是一个简单的方法:

fetch('https://example.com/login', {
    method: 'POST',
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
    },
    body: new URLSearchParams({
        'userName': 'test@gmail.com',
        'password': 'Password!',
        'grant_type': 'password'
    })
    .toString()
})
.then(res => {
    //Deal with response:
})
Run Code Online (Sandbox Code Playgroud)


ale*_*511 11

更简单:

body: new URLSearchParams({
      'userName': 'test@gmail.com',
      'password': 'Password!',
      'grant_type': 'password'
    }),
Run Code Online (Sandbox Code Playgroud)

  • 最佳答案,简短,不需要库,参考文档,+1 (11认同)
  • @lasseschou 不确定是否有必要:fetch 文档说 body 可以是 URLSearchParams (9认同)
  • 您需要在传递到“body”之前调用“.toString()” (5认同)
  • 这不会自动添加标头 `'Content-Type': 'application/x-www-form-urlencoded`,对吧? (4认同)
  • 您还可以传递一个 formdata 对象,因此当使用 HTML 表单时,即更短的“new URLSearchParams(formData)” (3认同)
  • 确实是最好的答案,并且 URLSearchParams 确实是 javascript 原生的 (2认同)
  • @B''HBi'ezras--BoruchHashem,没有库,一切都是内置的 (2认同)

ikh*_*vjs 10

您可以使用FormDataURLSearchParams来发布,如下application/x-www-form-urlencoded例所示:

如果您有表格:

<form>
    <input name="username" type="text" />
    <input name="password" type="password" />
    <button type="submit">login</button>
</form>
Run Code Online (Sandbox Code Playgroud)

您可以添加使用下面的 JS 来提交表单。

const form = document.querySelector("form");

form.addEventListener("submit", async () => {
    const formData = new FormData(form);
    try {
        await fetch("https://example.com/login", {
            method: "POST",
            headers: {
                "Content-Type": "application/x-www-form-urlencoded",
            },
            body: new URLSearchParams(formData),
        });
    } catch (err) {
        console.log(err);
    }
});
Run Code Online (Sandbox Code Playgroud)

  • 仅供参考,您不需要设置“content-type”标头。请参阅[此答案](/sf/answers/4805074361/) (3认同)

Tra*_*oud 9

无需使用 jQuery,querystring也无需手动组装有效负载。URLSearchParams是一种方法,这里是完整请求示例中最简洁的答案之一:

fetch('https://example.com/login', {
  method: 'POST',
  body: new URLSearchParams({
    param: 'Some value',
    anotherParam: 'Another value'
  })
})
  .then(response => {
    // Do stuff with the response
  });
Run Code Online (Sandbox Code Playgroud)

使用async/的相同技术await

const login = async () => {
  const response = await fetch('https://example.com/login', {
    method: 'POST',
    body: new URLSearchParams({
      param: 'Some value',
      anotherParam: 'Another value'
    })
  })

  // Do stuff with the response
}
Run Code Online (Sandbox Code Playgroud)

是的,您可以使用 Axios 或任何其他 HTTP 客户端库代替 native fetch


小智 7

*/ import this statement */
import qs from 'querystring'

fetch("*your url*", {
            method: 'POST',
            headers: {'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'},
            body: qs.stringify({ 
                username: "akshita",
                password: "123456",
            })
    }).then((response) => response.json())
      .then((responseData) => {
         alert(JSON.stringify(responseData))
    })
Run Code Online (Sandbox Code Playgroud)

使用npm i querystring --save 后,它工作正常。


mah*_*a k 7

var details = {
    'userName': 'test@gmail.com',
    'password': 'Password!',
    'grant_type': 'password'
};

var formBody = [];
for (var property in details) {
  var encodedKey = encodeURIComponent(property);
  var encodedValue = encodeURIComponent(details[property]);
  formBody.push(encodedKey + "=" + encodedValue);
}
formBody = formBody.join("&");

fetch('http://identity.azurewebsites.net' + '/token', {
  method: 'POST',
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/x-www-form-urlencoded'
  },
  body: formBody
})
Run Code Online (Sandbox Code Playgroud)

它对我很有帮助,而且没有任何错误

参考:https : //gist.github.com/milon87/f391e54e64e32e1626235d4dc4d16dc8


P-A*_*P-A 6

刚刚做了这个和UrlSearchParams做了诀窍这是我的代码,如果它可以帮助某人

import 'url-search-params-polyfill';
const userLogsInOptions = (username, password) => {



// const formData = new FormData();
  const formData = new URLSearchParams();
  formData.append('grant_type', 'password');
  formData.append('client_id', 'entrance-app');
  formData.append('username', username);
  formData.append('password', password);
  return (
    {
      method: 'POST',
      headers: {
        // "Content-Type": "application/json; charset=utf-8",
        "Content-Type": "application/x-www-form-urlencoded",
    },
      body: formData.toString(),
    json: true,
  }
  );
};


const getUserUnlockToken = async (username, password) => {
  const userLoginUri = `${scheme}://${host}/auth/realms/${realm}/protocol/openid-connect/token`;
  const response = await fetch(
    userLoginUri,
    userLogsInOptions(username, password),
  );
  const responseJson = await response.json();
  console.log('acces_token ', responseJson.access_token);
  if (responseJson.error) {
    console.error('error ', responseJson.error);
  }
  console.log('json ', responseJson);
  return responseJson.access_token;
};
Run Code Online (Sandbox Code Playgroud)