【发布时间】: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