【问题标题】:Create POST Request using JS使用 JS 创建 POST 请求
【发布时间】:2022-11-17 21:44:26
【问题描述】:

我想从我的网站向我的后端发送一个 POST 请求。但我收到以下错误: blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

我的代码

const response = await fetch("http://172.18.6.249:8090/test", {
          method: 'POST',
          headers: {
              'Accept': 'application/json',
              'Content-Type': 'application/json'
          },
          body: `{
 "Id": 78912,
 "Customer": "Jason Sweet",
 "Quantity": 1,
 "Price": 18.00
}`,
      });

      response.json().then(data => {
          console.log(data);
      });

服务器目前不使用任何类型的身份验证。

我怎样才能避免这个错误?

【问题讨论】:

    标签: javascript post fetch-api


    【解决方案1】:

    CORS 策略非常重要,是安全的一部分。
    在你的情况下,如果你想忽略 CORS,那么你可以使用这个:模式:“无科尔”在获取Api

    如果此问题仍然存在,则此 CORS 策略已在您的后端注册。因此,您无法从您的 IP 地址命中请求。

    下面是前端代码示例:

    const response = await fetch("http://172.18.6.249:8090/test", {
              method: 'POST',
              mode : "no-cors",
              headers: {
                  'Accept': 'application/json',
                  'Content-Type': 'application/json'
              },
              body: `{
                   "Id": 78912,
                   "Customer": "Jason Sweet",
                   "Quantity": 1,
                   "Price": 18.00
              }`,
          });
    
          response.json().then(data => {
              console.log(data);
          }); 
    

    【讨论】:

      猜你喜欢
      • 2019-01-09
      • 1970-01-01
      • 1970-01-01
      • 2020-08-01
      • 1970-01-01
      • 2023-03-09
      • 1970-01-01
      • 1970-01-01
      • 2012-04-05
      相关资源
      最近更新 更多