6

所以我正在发布一些 ajax 帖子,它似乎在 localhost 上运行良好,但是当我将它发布到亚马逊上的 ec2 服务器时,我得到 Uncaught SyntaxError: Unexpected token B. 这似乎指向 JSON 解析失败。完全相同的数据库、相同的浏览器和相同的方法被调用。为什么它可以在本地而不是在服务器上工作。

$.ajax({
                url: '@Url.Action("Action")',
                type: "POST",
                data: ko.toJSON(viewModel),
                dataType: "json",
                contentType: "application/json; charset:utf-8",
                success: function (result) {

                },
                error: function (xhr, textStatus, errorThrown) {
                    var errorData = $.parseJSON(xhr.responseText);
                    var errorMessages = [];

                    for (var key in errorData)
                    {
                        errorMessages.push(errorData[key]);
                    }
                    toastr.error(errorMessages.join("<br />"), 'Uh oh');
                }
            });

这是服务器端的基本布局:

[HttpPost]
        public JsonResult Action(ViewModel model)
        {
            try
            {

                Response.StatusCode = (int)HttpStatusCode.OK;
                return Json("Successfull");
            }
            catch (Exception ex)
            {
                logger.Log(LogLevel.Error, string.Format("{0} \n {1}", ex.Message, ex.StackTrace));
                Response.StatusCode = (int)HttpStatusCode.BadRequest;
                List<string> errors = new List<string>();
                errors.Add(ex.Message);
                return Json(errors);
            }

        }

try语句中,我对数据库进行了几次查询,并在Authorize.Net ( https://api.authorize.net/soap/v1/Service.asmx )上发布了一些计算

如果 Authorize.net Web 服务调用有任何错误,那么我会返回如下错误:

if (profile.resultCode == MessageTypeEnum.Error)
{
     logger.Log(LogLevel.Error, string.Join(",", profile.messages.Select(x => x.text)));
     Response.StatusCode = (int)HttpStatusCode.BadRequest;
     List<string> errors = new List<string>();
     profile.messages.ToList().ForEach(x => errors.Add(x.text));
     db.SaveChanges();
     return Json(errors);
}

我正在记录的这个错误:

    A public action method 'AddPromoCode' was not found on controller 'Flazingo.Controllers.PositionController'. at 
System.Web.Mvc.Controller.HandleUnknownAction(String actionName) at 
System.Web.Mvc.Controller.ExecuteCore() at 
System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) at
System.Web.Mvc.MvcHandler.<>c__DisplayClass6.<>c__DisplayClassb.b__5() at 
System.Web.Mvc.Async.AsyncResultWrapper.<>c__DisplayClass1.b__0() at 
System.Web.Mvc.MvcHandler.<>c__DisplayClasse.b__d() at 
System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() at 
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& 

同步完成)

4

4 回答 4

6

你有另一篇文章can't find action only on live server, works fine in local server,所以我猜这篇文章与 javascript 部分特别相关,而不是服务器端部分。

听起来服务器上发生了一些不好的事情,服务器发回了某种类型的错误,并且您的错误处理程序(在 javascript 中)在尝试处理该响应时死亡。

我得到 Uncaught SyntaxError: Unexpected token B. 这似乎指向 JSON 解析失败。

这听起来很合理。让我们看一下代码:

.ajax({
  ...
  error: function (xhr, textStatus, errorThrown) {
      var errorData = $.parseJSON(xhr.responseText);
      var errorMessages = [];
      ...
  },
  ...
});

我强烈建议看看是什么xhr.responseText。我猜它不包含有效的 JSON,因此 parseJSON 方法会引发“意外令牌 B”错误。

要查看此值,您可以console.log(xhr.responseText);在 Web 浏览器或 fiddler 中放置或使用诸如 javascript 调试器之类的工具来查看其中的内容。

我的猜测是服务器正在发回一个字符串,There was an error on the server而不是你期望的 JSON。我看到您内置了错误处理 - 我的猜测是您的错误处理中存在错误,并且没有什么可以捕获它。我建议在服务器端进行调试,看看是否有你不期望的错误。

也许 profile.messages 只能枚举一次,当您再次尝试这样做时,它会引发错误。或者也许 DB.SaveChanges 出于某种原因引发了错误。其中任何一个都会导致您在客户端看到的行为所记录的消息。

于 2013-04-25T02:21:59.253 回答
5

您正在尝试使用您自己的自定义响应内容返回 400 响应(错误请求)。

我认为默认情况下 IIS 不允许您这样做,并且正如 CodeThug 所提到的,可能正在用服务器消息替换您的自定义 JSON 内容。

但似乎您可以覆盖此行为:

http://develoq.net/2011/returning-a-body-content-with-400-http-status-code/

<system.webServer>
    <httpErrors existingResponse="PassThrough"></httpErrors>
</system.webServer>
于 2013-04-29T03:25:32.150 回答
2

过去,在淘汰和引导程序中使用 ASP.NET 脚本捆绑时,我收到过类似的神秘错误,尤其是在捆绑中包含已经缩小的版本时。

如果您在本地主机上以调试模式运行,那么 ASP.NET 将不会缩小 javascript 库。但是,一旦部署,您可能不再处于调试模式,现在正在缩小/捆绑脚本。有时,这些脚本的捆绑/缩小可能会导致类似于您发布的语法错误。

如果是这样,您可以从 CDN 加载淘汰赛以避免捆绑。

于 2013-04-27T06:34:35.190 回答
0

似乎 JSON 正在发送,因为来自服务器的响应生成错误

ex: if a value in the database is hi "my" friends

    JSON file will be generated as text:"hi "my" friends"

因此属性文本的值生成错误。

在生产/开发服务器中仔细检查这些值。

最佳做法是用转义字符替换引号

ex: text:"hi \"my\" friends"
于 2013-07-08T18:39:51.200 回答