Axios请求与传统表格提交请求相同

时间:2019-01-06 01:15:25

标签: javascript html axios

我正在尝试连接到外部API。当我尝试使用具有以下提交内容的经典html表单标记来实现这一点时,这很容易:

<form action="https://sandbox.przelewy24.pl/trnRegister" method="post" className="form">
  <input type="text" name="p24_session_id" value={this.state.UUID}/>
  <input type="text" name="p24_merchant_id" value="79305"/>
  <input type="text" name="p24_pos_id" value="79305"/>
  <input type="text" name="p24_amount" value="100"/>
  <input type="text" name="p24_currency" value="PLN"/>
  <input type="text" name="p24_description" value="TYTUŁ"/>
  <input type="text" name="p24_client" value="Jan Kowalski"/>
  <input type="text" name="p24_address" value="ul. Polska 33/33"/>
  <input type="text" name="p24_zip" value="66-777"/>
  <input type="text" name="p24_city" value="Poznań"/>
  <input type="text" name="p24_country" value="PL"/>
  <input type="text" name="p24_email" value="email@host.pl"/>
  <input type="text" name="p24_language" value="pl"/>
  <input type="text" name="p24_url_return" value="http://myhost.pl/skrypt_ok.php"/>
  <input type="text" name="p24_api_version" value="3.2"/>
  <input type="hidden" name="p24_sign" value={md5(`${this.state.UUID}|123|100|PLN|123123123`)}/>
  <input name="submit_send" value="wyślij" type="submit" />
</form>

它工作正常。但是我想通过axios使用post request实现相同的目的。因此,我将所有的值都放在对象中。

    const paymentDetailsObj = {
        p24_amount,
        p24_currency,
        p24_description: formattedTitle,
        p24_email: email,
        p24_country: 'PL',
        p24_url_return: 'https://malewielkieprzygody/thankyou',
        p24_url_status: `${baseApiURL}verifypayment`,
        p24_transfer_label: formattedTitle,
        p24_api_version: '3.2',
        p24_merchant_id: 123,
        p24_pos_id: 123,
        p24_session_id: UUI,
        p24_sign: md5(checksum),
    };

...并与axios一起发送...

  const res = axios.post(`https://secure.przelewy24.pl/trnRegister`, paymentDetailsObj);

那不起作用,浏览器显示:

Access to XMLHttpRequest at 'https://secure.przelewy24.pl/trnRegister' from origin 'http://localhost:3001' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

我认为我了解CORS政策的概念。我尝试向请求中添加一些标头,但它也失败,并显示相同的错误:

const res = axios.post(`https://secure.przelewy24.pl/trnRegister`, paymentDetailsObj, {
  mode: 'no-cors',
  headers: {
    'Access-Control-Allow-Origin': '*',
    Accept: 'application/json',
    'Content-Type': 'multipart/form-data',
  },
  withCredentials: true,
  credentials: 'same-origin',
  crossdomain: true,
});

现在,如何使用axios实现模仿旧式表单请求? 谢谢

1 个答案:

答案 0 :(得分:0)

您正在从所请求的来源获得CORS问题,并且我想您想创建一个CORS代理以使其正常工作。我坚信这篇文章将为您提供帮助:sideshowbarker's answer here