简体   繁体   中英

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. The request works from Postman, so the URL is correct. 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 ()".

Sending the same request from localhost to a postman mock-server also works.

This is my HTML file:

<!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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM