【问题标题】:API call working through server side code (node.js, php) but not through JS in browser using fetch()API调用通过服务器端代码(node.js,php)而不是通过浏览器中的JS使用fetch()
【发布时间】:2019-10-17 16:30:47
【问题描述】:

我正在尝试通过 fetch() 发出 API POST 请求。当我在服务器端( PHP 或 Node.js )执行它时,它可以正常工作。尝试在浏览器中执行它时出现两个错误: 1) 405 错误 - 方法不允许 2) CORS 策略已阻止从源“null”获取“url”的访问权限:对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头.如果不透明的响应满足您的需求,请将请求的模式设置为“no-cors”以获取禁用 CORS 的资源。

我尝试添加:模式:“no-cors”。然后我收到以下错误: “401 未经授权” 回复如下: 401 response

这是我的标准 js 设置:

const TrailData = {
      email: "test@test.com",
      first_name: "sample string 5",
      last_name: "sample string 6",
      phone2: "12121212"
    };


    // TRAIL POST ( NOT WORKING )
    fetch('http://webapi.mymarketing.co.il/api/contacts', {
            method: "POST",
            mode: 'no-cors',
            headers: {
              "Authorization": "API CODE //here comes the API CODE",
              "Content-Type": "application/json"
            },
            body: JSON.stringify(TrailData)
          })
          .then(res => console.log(res) )
          .then(data => console.log(data))
          .catch(err => console.log(err))

我的 Node js 设置是:

var postData = {

    sms_status: "None",
    email: "test@test.com",
    first_name: "sample string 5",
    last_name: "sample string 6", 
  };

  let axiosConfig = {
headers: {
    "Authorization": "API CODE",
    'Content-Type': 'application/json;charset=UTF-8',
    "Access-Control-Allow-Origin": "*",
}
  };


const Trail = async () =>{
try {
    const response = await axios.post('http://webapi.mymarketing.co.il/api/contacts', postData, axiosConfig)
    console.log(response)
} catch (error) {
    throw new Error(error)
}


  }

 Trail()

Node JS 有效。我得到 200 OK 响应。第一个没有!

API 是否有可能阻止来自浏览器的请求? 我尝试了很多方法,每次使用浏览器都失败了。

感谢您的帮助!

【问题讨论】:

  • 我认为您必须在禁用 cors 的情况下运行浏览器,或者运行一些本地服务器来提供这些文件。
  • 可以这样限制API吗? ,因为当用另一个 API 尝试相同的代码时,它可以完美地工作......

标签: javascript node.js api fetch


【解决方案1】:

如果没有 CORS(Authorization 标头),您将无法发送额外的标头

因为服务器不响应预检请求,所以不允许您发送该请求

如果没有 CORS,您只能发送“简单请求”,请参阅 https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#Simple_requests

https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

https://developer.mozilla.org/en-US/docs/Glossary/Preflight_request

更多信息

【讨论】:

  • 感谢您的回复!这是否意味着,必须在 API 服务器端进行配置才能允许这样做?并且通过 node.js 没有 CORS?
  • 是的 CORS(预检请求处理)需要在后端(服务器端)进行配置,不管后端写什么任何东西都可以处理 CORS ... CORS 只是浏览器的东西,所以其他平台(服务器端,桌面/移动应用程序)不关心它
猜你喜欢
  • 2019-11-11
  • 1970-01-01
  • 2012-05-28
  • 1970-01-01
  • 1970-01-01
  • 2014-04-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多