React表单提交实例(POST请求)
最近在做一个项目,需要在react后端页面实现点击按钮,跳转商城页面。
1.尝试用fetch请求
var url = "https://test.taobao.com/login";
let options = {};
var headers = new Headers();
headers.append( "Content-Type", "application/x-www-form-urlencoded");
options.headers = headers;
options.body = res.result;
options.method = "POST";
options.credentials = "include";
options.mode = "cors";
return fetch(url, options).then((response) => {
});
提示跨域错误。
2.改为react表单提交
makeForm:function(data){
//console.log(data);
const form = document.createElement('form');
form.id = 'form-file-download';
form.name = 'form-file-download';
// 添加到 body 中
document.body.appendChild(form);
for (const key in query) {
if (query[key]!== undefined && Object.hasOwnProperty.call(query, key)) {
// 创建一个输入
const input = document.createElement('input');
input.type = 'hidden';
input.name = key;
input.value = query[key];
form.appendChild(input);
}
}
// form 的提交方式
form.method = 'POST';
//跳转新页面
form.target = '_blank'
// form 提交路径
form.action = 'https://test.taobao.com/login';
form.submit();
document.body.removeChild(form);},
data为页面所需json,后台得到即可。