Reputation: 3451
I have the following angularjs code:
$http.get("/Home/GetEmails").then(function (response) {
$scope.emails = response.data;
$scope.init($scope.emails);
$scope.totalEmails = $scope.emails.length;
});
When I develop locally, it works fine, but when I publish to a live server, it gives the following error message:
Failed to load resource: the server responded with a status of 404 (Not Found)
. It is looking for http://xaisoft.com/Home/GetEmails, but it can't find it. Is there something else I need to do in ASP.NET MVC and/or Angular to get this to work. Currently, I just have the GetEmails action return a JSON object in my HomeController.
HomeController
public class HomeController : Controller
{
//
// GET: /Home/
public ActionResult Index()
{
return View();
}
public ActionResult GetEmails()
{
return Json(new[]
{
new
{
from = "Jet Blue",
to = "Me",
subject = "Buy one seat, get one free!",
body = "That and helping Data finish 'Pop Goes the Weasel'. Also counts as a CMOH.",
date = "Dec 20th 12:22 PM",
isImportant = false,
isStarred = true,
isChecked = false,
isRead = true
},
new
{
from = "Publix",
to = "Me",
subject = "Check this weeks BOGO deals",
body = "Hurry, ends Thursday!",
date = "Mar 15th 8:15 AM",
isImportant = false,
isStarred = false,
isChecked = false,
isRead = false
},
new
{
from = "AJ Carpio",
to = "Me",
subject = "When Life Gives You Questions, Google has Answers",
body = "Get more life quotes here",
date = "Mar 15th 8:15 AM",
isImportant = true,
isStarred = false,
isChecked = false,
isRead = true
}
},JsonRequestBehavior.AllowGet);
}
}
Upvotes: 1
Views: 1939
Reputation: 1038830
You should never hardcode urls in an ASP.NET MVC application as you did:
$http.get("/Home/GetEmails")
You should always use url helpers. For example in your view you could set a variable:
<script type="text/javascript">
var getEmailsUrl = @Url.Action("GetEmails", "Home");
</script>
that you could later use in your ng script:
$http.get(getEmailsUrl)
The purpose of Url helpers such as Url.Action
is to take into account things like the hosting environment virtual directory and your routing configuration. All those factors could change between the various environments and if you hardcode your urls in your javascript you will pretty much get lots of 404s.
Here's a more angular way of doing this instead of registering a global javascript variable. You could use the $provide
:
<script type="text/javascript">
angular.module('myApp').config(['$provide', function ($provide) {
// Here you can also register a complex javascript object that will serve
// as configuration for your app and can contain multiple urls
$provide.value('getEmailsUrl', '@Url.Action("GetEmails", "Home")');
}]);
</script>
and then you can inject the getEmailsUrl
in your controllers and services:
app.controller('HomeController', ['$scope', 'getEmailsUrl', function ($scope, getEmailsUrl) {
// You can use the getEmailsUrl variable here.
}]);
Upvotes: 2