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 的后请求来实现相同的目标。所以我把我所有的价值观都打包到对象里。

    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),
    };

。并用公理发送它...

  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 实现来模仿老式的表单请求?谢谢

您从请求的来源收到 CORS 问题,我假设您想创建一个 CORS 代理以使其正常工作。我坚信这篇文章会对你有所帮助:Sideshowbarker的答案在这里

最新更新