Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
129 views
in Technique[技术] by (71.8m points)

AJAX call to an Action with Authorize attribute in .NET Core 3.1

On my pet project (a lyrics website), I wish to add "like" functionality, like this:

screenshot showing like button

Code is open source (here's my current branch). A click on the heart icon should add a like to the databse for the logged in user, and if the user isn't logged in, it should redirect to the login page (IdentityServer 4, separate project and domain).

Controller Action:

[Authorize]
[Route("lyrics/like/{lyricId}")]
public async Task<IActionResult> Like(
  int lyricId)
{
  try
  {
    string userId = User.GetUserId().ToString();

    await _lyricsService.LikeLyricAsync(userId, lyricId);

    return RedirectToAction("Index", "Home");
  }
  catch
  {
    return RedirectToAction("Index", "Home");
  }
}

JavaScript on the View:

<script>
  docReady(function () {
    let likeBtn = document.getElementById('like-btn');

    let likeLyric = (event) => {
      event.preventDefault();
      console.log('attemping to like a lyric!');

      // 1. create a new XMLHttpRequest object
      let request = new XMLHttpRequest();

      // 2. configure the request
      request.open('GET', 'https://localhost:5001/lyrics/like/@Model.Id');

      // 3. send the request over the network
      request.send();

      // 4. this will be called after the response is received
      request.onload = function () {
        if (request.status != 200) {
          // analyse http status of the response
          alert(`Error ${request.status}: ${request.statusText}`);
        } else {
          // show the result
          alert(`Done, got ${request.response.length} bytes`); // response is the server response
        }
      };

      request.onprogress = function (event) {
        if (event.lengthComputable) {
          alert(`Received ${event.loaded} of ${event.total} bytes`);
        } else {
          alert(`Received ${event.loaded} bytes`); // no Content-Length
        }
      };

      request.onerror = function () {
        alert("Request failed");
      };
    }

    likeBtn.addEventListener('click', likeLyric);
  });
</script>

I tried to expand on the request.onload function by adding an:

else if (request.status === 302) {
  window.location = request.response;
}

But it doesn't seem to get to that, the .send() fails. What am I doing wrong here?

Here's a screen grab of what is happening:

enter image description here

The error is:

attemping to like a lyric!
govenda-sera:1 Access to XMLHttpRequest at 'https://localhost:5006/connect/authorize?client_id=bejebeje-mvc-local&redirect_uri=https%3A%2F%2Flocalhost%3A5001%2Fsignin-oidc&response_type=code&scope=openid&code_challenge=2mUDM3-gR1jhn7E2EY7T17FkPTHikE8v-KQOBMskazM&code_challenge_method=S256&response_mode=form_post&nonce=637437449511000684.OWQ3MTM4MjItOTJhOS00YjgzLTk1OTYtYWE2ZGUyMzRlYzUyOWE1MTkwNjgtNzI2YS00OWJjLTgzYjAtOTY1MDQ1ZDU3YzE1&state=CfDJ8DxKnFiqfK1HscY3j3s4hc-YvLoUa_X_46X1CclU7U-RahgrNQULQOLJu6943zTWCYa5Q5acO7g7vx03ddXSOOKkUtxZQAMHSgnQHFzBvhXnoC2i6yS0PpGxns7oA7tuvcgnp-jxub7RePZl5QAe5BwfXWkyHtMkFAmTkuultwz5w-Duenyb4KNrZRk1RLn6TLL93BS6YfIfoozorOnvKel4cFFjxIc7F_QXgVFKZm6ud5lN2nItw5WhkDfU6qMHhUUSQXQRJqWSit4CW_1hPpbHZhJmatXWxD8mLVFcSEKMNQz2UIU00RDxBCQW09Skuy3Uoz50Vwp4dEYPtNIcolIKrLn1pJguNsYRWBw391uWO7rMy9W5DPJV44fMVe8UR5xKNUarkelFX4CzHidF-rE&x-client-SKU=ID_NETSTANDARD2_0&x-client-ver=5.5.0.0' (redirected from 'https://localhost:5001/lyrics/like/938') from origin 'https://localhost:5001' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
govenda-sera:131 GET https://localhost:5006/connect/authorize?client_id=bejebeje-mvc-local&redirect_uri=https%3A%2F%2Flocalhost%3A5001%2Fsignin-oidc&response_type=code&scope=openid&code_challenge=2mUDM3-gR1jhn7E2EY7T17FkPTHikE8v-KQOBMskazM&code_challenge_method=S256&response_mode=form_post&nonce=637437449511000684.OWQ3MTM4MjItOTJhOS00YjgzLTk1OTYtYWE2ZGUyMzRlYzUyOWE1MTkwNjgtNzI2YS00OWJjLTgzYjAtOTY1MDQ1ZDU3YzE1&state=CfDJ8DxKnFiqfK1HscY3j3s4hc-YvLoUa_X_46X1CclU7U-RahgrNQULQOLJu6943zTWCYa5Q5acO7g7vx03ddXSOOKkUtxZQAMHSgnQHFzBvhXnoC2i6yS0PpGxns7oA7tuvcgnp-jxub7RePZl5QAe5BwfXWkyHtMkFAmTkuultwz5w-Duenyb4KNrZRk1RLn6TLL93BS6YfIfoozorOnvKel4cFFjxIc7F_QXgVFKZm6ud5lN2nItw5WhkDfU6qMHhUUSQXQRJqWSit4CW_1hPpbHZhJmatXWxD8mLVFcSEKMNQz2UIU00RDxBCQW09Skuy3Uoz50Vwp4dEYPtNIcolIKrLn1pJguNsYRWBw391uWO7rMy9W5DPJV44fMVe8UR5xKNUarkelFX4CzHidF-rE&x-client-SKU=ID_NETSTANDARD2_0&x-client-ver=5.5.0.0 net::ERR_FAILED
likeLyric
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can't do an AJAX call to this URL to login the user:

https://localhost:5006/connect/authorize?....

If you want the user to login/authenticate, then you need to redirect the browser to that page.

Or better, don't show the heart icon if the user is not logged in, better to have a login to like button? The user might otherwise be surprised why he needs to login.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...