[英]Post request returns 401 from localhost but works from postman
I am trying to send API calls via POST-Request using th JavaScript fetch-API and Basic Authorization.我正在尝试使用 JavaScript fetch-API 和基本授权通过 POST-Request 发送 API 调用。 The request works from Postman, so the URL is correct.
该请求来自 Postman,因此 URL 是正确的。 However, sending the request from localhost using VS Code Live Server Extension, the request returns "Failed to load resource: the server responded with a status of 401 ()".
但是,使用 VS Code Live Server Extension 从本地主机发送请求时,请求返回“无法加载资源:服务器响应状态为 401 ()”。
Sending the same request from localhost to a postman mock-server also works.将相同的请求从本地主机发送到邮递员模拟服务器也可以。
This is my HTML file:这是我的 HTML 文件:
<!DOCTYPE html>
<html>
<head>
<title>Title</title>
</head>
<body>
<input id="name" type="text" name="name" placeholder="name">
<input type="text" id="username" name="username">
<input type="password" id="password" name="password">
<button type="submit" onclick=JSONTest()> Submit </button>
<script type="text/javascript">
JSONTest = function() {
var name = document.getElementById("name").value;
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
let data = {title: name};
fetch("url", {
mode: 'no-cors',
method: "POST",
headers: {'Content-Type': 'application/json', 'Authorization': 'Basic ' + btoa(username + ":" + password)},
body: JSON.stringify(data)
}).then(res => {
console.log("Request complete! response:", res);
});
};
</script>
</body>
</html>
Based on the information you have provided I am inclined to say it is likely a CORS issue.根据您提供的信息,我倾向于说这可能是CORS问题。 Without more information about the url you are trying to access it is hard to say what exactly the issue may be.
如果没有关于您尝试访问的网址的更多信息,很难说出问题到底是什么。
It could also have to do with the protocol being used, make sure that you are using HTTPS if it is required.它还可能与正在使用的协议有关,如果需要,请确保您使用的是 HTTPS。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.