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