【问题标题】:Why a Get request is fired from a Post request when using fetch?为什么在使用 fetch 时从 Post 请求中触发 Get 请求?
【发布时间】:2019-05-21 01:20:41
【问题描述】:

我正在使用 MVC 我正在使用 javascript fetch 向控制器发出 POST 请求,结果控制器工作正常,但是一旦 POST 请求完成,我就会收到错误GET 请求!

GET http://localhost:50404/users/%40Tahboub96 404 (Not Found)

这是获取的 JavaScript 代码:

const followFunc = () => {
            document.getElementById('followbtn').addEventListener('click', async () => {
                const followPost = await fetch(`/users/handlefollow/${userId}`, {
                    method: 'POST', 
                    mode: 'cors', 
                    cache: 'no-cache', 
                    credentials: 'same-origin', 
                    headers: {
                        'Content-Type': 'application/json',

                    },
                    redirect: 'follow', 
                    referrer: 'no-referrer', 
                    body: JSON.stringify(userId), 
                })
                    .then(() => {
                        document.getElementById('followbtn').textContent = "Un-Follow";
                    });

            });
        };

        followFunc();

这是我的操作结果代码:

[HttpPost]
        public ActionResult HandleFollow(string id)
        {
            //id param is the id of the follower

            //You
            var followerId = User.Identity.GetUserId();
            var follower = _context.Users.FirstOrDefault(x => x.Id == followerId);

            //Who to follow
            var following = _context.Users.FirstOrDefault(x => x.Id == id);

            //add a following to the follower
            if(follower.Following == null)
                follower.Following = 0;

            follower.Following += 1;
            //

            //add a follower to the following
            if (following.Follower == null)
                following.Follower = 0;

            following.Follower += 1;
            //

            //add the transaction to the follow table
            var followTable = new Follow();
            followTable.FollowerId = followerId;
            followTable.FollowingId = id;

            //add it to db
            _context.Follows.Add(followTable);

            //save changes to db
            _context.SaveChanges();

            return RedirectToAction("@" + following.UserName);
        }

【问题讨论】:

  • RedirectToAction("@" + following.UserName) 正在重定向到该路径,这将作为 GET 触发。
  • @Herohtar 你说得对,非常感谢! :D

标签: javascript model-view-controller fetch


【解决方案1】:

您的 MVC 操作正在返回重定向指令。 您的 POST 选项包括

重定向:“关注”,

所以它遵循重定向指令。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-03-24
    • 2017-06-05
    • 1970-01-01
    • 2015-08-06
    • 2017-06-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多