Angular JS - Error: $http:badreq Bad Request Configuration - javascript

I am learning Angular JS. I am trying to create a mock portal that displays Daily Messages. I have stored my daily messages in a database table.
create table DailyMsg(Sno int primary key, msg varchar(max));
Then I created a service using factory in AngularJS.
public class DailyMsgsController : Controller
{
private amenEntities1 db = new amenEntities1();
// GET: DailyMsgs
public ActionResult Index()
{
return Json(db.DailyMsgs.ToList(),JsonRequestBehavior.AllowGet);
}
}
I tested the URL and it works fine, it returns the expected data in the JSON format
https://localhost:44329/DailyMsgs
Now, I wanted to display this data on my HomePage. But it doesn't work. On inspecting the page it shows me the error
Error: $http:badreq
Bad Request Configuration
Http request configuration url must be a string or a $sce trusted object. Received: undefined
My Controller
var myApp = angular.module('myApp', []);
//Daily Messages Service Function
myApp.factory('DailyMsgService', function ($http) {
DailyMsgObj = {};
DailyMsgObj.DisplayDailyMsg = function () {
var Msg;
Msg = $http({method: 'GET', URL: '/DailyMsgs/Index'}).
then(function (response){
return response.data;
});
return Msg;
}
return DailyMsgObj;
});
myApp.controller('HomePageController', function ($scope, DailyMsgService) {
DailyMsgService.DisplayDailyMsg().then(function (result) {
$scope.DailyMsg = result;
});
});
My HomePage
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<div ng-controller="HomePageController">
{{DailyMsg}}
</div>
</body>
</html>
<script src="../Scripts/angular.min.js"></script>
<script src="../Scripts/bootstrap.min.js"></script>
<link href="../Content/bootstrap.min.css" rel="stylesheet" />
<script src="../AngularControllers/HomePageController.js"></script>

Related

Unable to Connect to Spotify Api :Error Invalid URI Response

I am using the following two files attached.
index2.html file located on the local server which is calling the JavaScript file which is also located on the local machine
fetch-ajax3.js - JavaScript file located on the local server consisting of the function and method to authenticate and authorize the API call and retreive data and post it in the console.
I am not sure what to input in redirect URI.
Can someone help?
Resolution - i was able to resolve the issue after whitelisting the callback uri in the spotify api app.
const hash = window.location.hash
.substring(1)
.split('&')
.reduce(function (initial, item) {
if (item) {
var parts = item.split('=');
initial[parts[0]] = decodeURIComponent(parts[1]);
}
return initial;
}, {});
window.location.hash = '';
// Set token
let _token = hash.access_token;
const authEndpoint = 'https://accounts.spotify.com/authorize';
// Replace with your app's client ID, redirect URI and desired scopes
const clientId = '';
const redirectUri = '';
const scopes = [
'user-top-read'
];
// If there is no token, redirect to Spotify authorization
if (!_token) {
window.location = `${authEndpoint}?client_id=${clientId}&redirect_uri=${redirectUri}&scope=${scopes.join('%20')}&response_type=token&show_dialog=true`;
}
// Make a call using the token
$.ajax({
url: "https://api.spotify.com/v1/me/top/artists",
type: "GET",
beforeSend: function(xhr){xhr.setRequestHeader('Authorization', 'Bearer ' + _token );},
success: function(data) {
// Do something with the returned data
data.items.map(function(artist) {
let item = $('<li>' + artist.name + '</li>');
item.appendTo($('#top-artists'));
});
}
});
<html>
<head>
<title>Spotify Implicit Grant Template</title>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://sp-bootstrap.global.ssl.fastly.net/8.0.0/sp-bootstrap.min.css" rel="stylesheet" />
<script
src="https://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous"></script>
<script src="./fetch-ajax3.js" defer></script>
</head>
<body class="container">
<h1 class="text-salmon">Spotify Implicit Grant Template</h1>
<h3>This app uses the implicit grant authorization flow to authenticate users and get user data.</h3>
<p>
Here are your top artists on Spotify:
<ol id="top-artists"></ol>
</body>
</html>
After whitelisting the callback url in the app , i was able to connect it.
specify your URL as Http for localhost in the app settings in your Spotify dashboard
You need to add your URL in Redirect URI which will whitelist your URL. It works for me.

Spotify Implicit Grant won't work on node

I am trying to make the codes you see here:
https://glitch.com/edit/#!/amusing-swallow?path=index.html:7:68
executable on my node js application. Please note that the codes on that link is working.
What I did is that I set up an environment like this:
root folder
--public
--index.html
--script.js
--app.js
--package.json
And then I copied the html code to my index.html file like this:
<!DOCTYPE html>
<html>
<head>
<title>Spotify Implicit Grant Template</title>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://sp-bootstrap.global.ssl.fastly.net/8.0.0/sp-bootstrap.min.css" rel="stylesheet" />
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous"></script>
</head>
<body class="container">
<h1 class="text-salmon">Spotify Implicit Grant Template</h1>
<h3>This app uses the implicit grant authorization flow to authenticate users and get user data.</h3>
<p>
Here are your top artists on Spotify:
<ol id="top-artists"></ol>
</p>
<script src="../script.js" type='text/javascript'></script>
</body>
</html>
Nothing special and then I made the script.js a self invoking function like this:
(function() {
// Get the hash of the url
const hash = window.location.hash
.substring(1)
.split("&")
.reduce(function(initial, item) {
if (item) {
var parts = item.split("=");
initial[parts[0]] = decodeURIComponent(parts[1]);
}
return initial;
}, {});
window.location.hash = "";
// Set token
let _token = hash.access_token;
const authEndpoint = "https://accounts.spotify.com/authorize";
// Replace with your app's client ID, redirect URI and desired scopes
const clientId = "xxxxxxxxxxxxxxxxxxxxxxxx";
const redirectUri = "http://localhost:8888/callback/";
const scopes = ["user-top-read"];
// If there is no token, redirect to Spotify authorization
if (!_token) {
window.location = `${authEndpoint}?client_id=${clientId}&redirect_uri=${redirectUri}&scope=${scopes.join(
"%20"
)}&response_type=token&show_dialog=true`;
}
// Make a call using the token
$.ajax({
url:
"https://api.spotify.com/v1/search?query=tania+bowra&offset=0&limit=20&type=artist",
type: "GET",
beforeSend: function(xhr) {
xhr.setRequestHeader("Authorization", "Bearer " + _token);
},
success: function(data) {
// Do something with the returned data
data.items.map(function(artist) {
let item = $("<li>" + artist.name + "</li>");
item.appendTo($("#top-artists"));
});
}
});
})();
And then finally on my app.js for express:
var express = require("express"); // Express web server framework
var app = express();
app.use(express.static(__dirname + "/public"));
console.log("Listening on host 8888......");
app.listen(8888);
So I tried to run this and whenever I visit the localhost:8888, I keep on getting these:
GET http://localhost:8888/script.js 404 (Not Found)
Refused to execute script from 'http://localhost:8888/script.js' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled.
I am not sure why. But I just copied the same exact code and just put my credentials there but it won't still work. Any idea what am I doing wrong?

Angular $http service, Steam DotA 2 API

I just started out with AngularJS, and I have a question regarding $http service and receiving data from web server, I made this simple script that was supposed to get JSON from Steam's DotA2 API but for some reason it's not getting data, here are index.html and script.js respectively:
<html ng-app="steamPowered">
<head>
<script data-require="angular.js#1.3.0-beta.5" data-semver="1.3.0-beta.5" src="https://code.angularjs.org/1.3.0-beta.5/angular.js"></script>
<script src="script.js"></script>
<title>
Angular
</title>
</head>
<body ng-controller="MainController">
<div>
<p>{{errx}}</p>
</div>
<div>
<p>Player ID: {{levat.result.players[0].account_id}}</p>
</div>
</body>
</html>
script.js
(function() {
var nesscafe = angular.module("steamPowered", []);
var MainController = function($scope, $http) {
var apikey = "xxxxxxxxxxxxxxxxxxxxxxxxxx";
var matchID = prompt("Enter match ID: ")
var returnedObject = function(response) {
$scope.levat = response.data;
}
var onError = function() {
$scope.errx = "ERROR: https://api.steampowered.com/IDOTA2Match_570/GetMatchDetails/V001/?match_id=" + matchID + "&key=" + apikey;
} $http.get("https://api.steampowered.com/IDOTA2Match_570/GetMatchDetails/V001/?match_id=" + matchID + "&key=" + apikey)
.then(returnedObject, onError);
}
nesscafe.controller("MainController", MainController);
}());

How to connect signalR from angularJs

I am developing web application in .NET as two separate applications, back end using webapi c# and user interface using AngularJS. I just want to add Chat option in this project. I have installed SignalR and added ChatHub.cs class in webapi.
enter image description here
in WebAPI there is a class named Startup.cs
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
HttpConfiguration config = new HttpConfiguration();
config.Formatters.JsonFormatter.SerializerSettings.DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Local;
WebApiConfig.Register(config);
app.UseCors(CorsOptions.AllowAll);
ConfigureAuth(app);
app.UseWebApi(config);
app.MapSignalR();//added after installation of SignalR package
}
}
ChatHub class
public class ChatHub : Hub
{
public static string emailIDLoaded = "";
public void Connect(string userName, string email)
{
emailIDLoaded = email;
var id = Context.ConnectionId;
using (SmartCampEntities dc = new SmartCampEntities())
{
var userdetails = new ChatUserDetail
{
ConnectionId = id,
UserName = userName,
EmailID = email
};
dc.ChatUserDetails.Add(userdetails);
dc.SaveChanges();
}
}
}
Whatever request i send from user interface it will hit to its corresponding controller in webAPI. For example
$http({
method: 'GET',
url: $scope.appPath + "DashboardNew/staffSummary" //[RoutePrefix]/[Route]
}).success(function (result, status) {
data = result;
});
My user interface is a separate application. How can i connect signalR from UI.
I tried something but didn't get it work. Can anyone suggest me how to get it work
html code
<div>
<a class="btn btn-blue" ng-click="sendTask()">SendTask</a>
javascript
angular.module('WebUI').controller('DashboardCtrl', function ($scope, $window, $http, $modal, ngTableParams) {
$scope.header = "Chat";
$scope.sendTask = function () {
$http({
method: 'POST',
url: $scope.appPath + hubConnetion.server.sendTask("userName","email"),
})
}
});
Basics:
That you can connect to your signalr server you have to include the client code to your page. It's also important that you include jquery before.
At least you can also include the generate hubs file in the case you are working with hubs:
<script src="Scripts/jquery-1.10.2.min.js"></script>
<script src="Scripts/jquery.signalR-2.1.0.min.js"></script>
<script src="signalr/hubs"></script>
Basic Sample:
Here you have a full sample (without and with generated hub proxy):
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
</head>
<body>
<div class="container">
<div class="row">
<!-- Title -->
<h1>SignalR Sample</h1>
</div>
<div class="row">
<!-- Input /Button-->
<input type="text" id="inputMsg" />
<button button="btn btn-default" id="btnSend">Send</button>
</div>
<div class="row">
<!-- Message list-->
<ul id="msgList"></ul>
</div>
</div>
<script src="Scripts/jquery-1.6.4.js"></script>
<script src="Scripts/jquery.signalR-2.2.0.js"></script>
<script src="http://[LOCATIONOF YOUR HUB]/signalr/hubs"></script>
<script>
// ------------------- Generated Proxy ----------------------------
$(function () {
$.connection.hub.url = "[LOCATION WHERE YOUR SERVICE IS RUNNING]/signalr";
var chat = $.connection.myChat;
chat.client.addMessage = function (name, message) {
$('#msgList').append('<li><strong>' + name
+ '</strong>: ' + message + '</li>');
};
$.connection.hub.start({}).done(function () {
$('#btnSend').click(function () {
chat.server.Send("Stephan", $('#inputMsg').val());
$('#inputMsg').val('').focus();
});
})
});
//// ------------------- Without Proxy ----------------------------
//$(function () {
// var connection = $.hubConnection("http://localhost:8080/signalr");
// var chatHubProxy = connection.createHubProxy('chatHub');
// chatHubProxy.on('AddMessage', function (name, message) {
// console.log(name + ' ' + message);
// $('#msgList').append('<li><strong>' + name
// + '</strong>: ' + message + '</li>');
// });
// connection.start().done(function () {
// $('#btnSend').click(function () {
// chatHubProxy.invoke('send', "Stephan", $('#inputMsg').val());
// $('#inputMsg').val('').focus();
// });
// });
//});
</script>
</body>
</html>
For more details see:
http://www.asp.net/signalr/overview/guide-to-the-api/hubs-api-guide-javascript-client
SignalR Angular Module:
There is also a "helper module" which you can use in angularjs for working with signalr:
https://github.com/JustMaier/angular-signalr-hub
I can able to connect webapi by adding below code into my Startup.Auth.cs
public void ConfigureAuth(IAppBuilder app)
{
app.UseOAuthBearerTokens(OAuthOptions);
//by adding below code
app.UseCors(CorsOptions.AllowAll);
app.MapSignalR(new HubConfiguration { EnableJSONP = true });
}

How to load an object onload with angular

This is my html
<!DOCTYPE html>
<html x-ng-app="demo">
<head>
<title>Demo</title>
<script src="../demo/js/angular.js"></script>
<script src="../demo/js/jquery-3.1.0.js"></script>
<script src="../demo/js/jquery-3.1.0.min.js"></script>
<script src="../demo/js/bootstrap.js"></script>
<script src="../demo/js/bootstrap.min.js"></script>
<link href="../demo/css/bootstrap.css" rel="stylesheet">
<script src="../demo/js/employee_service.js"></script>
<script src="../demo/js/employee_controller.js"></script>
</head>
<body>
<form name="demo_form">
<div x-ng-controller="EmployeeController">
<h1> {{Employee.name}} </h1>
<span> </span>
<ul>
<li x-ng-repeat="address in employee.addresses">
{{address.address1}}
</li>
</ul>
</div>
</form>
</body>
</html>
This is my service script
var module = angular.module('demo', []);
module.service('EmployeeService', function($http){
this.get = function(id){
var method = "GET";
var url = "http://localhost:8080/rest/employee/get/" + id;
console.log(url);
$http({
method : method,
url : url,
headers: {'Content-Type' : 'application/json'}
}).then(onSuccess, onError);
function onSuccess(response){
console.log('got it');
return response.data;
}
function onError(response){
console.log(response.statusText);
}
}
});
This is my controller
//module.controller('EmployeeController', function ($scope, $routeParams EmployeeService) { //This line give an error but it is not related to the question
module.controller('EmployeeController', function ($scope, EmployeeService) {
//var paramEmployeeID = $routeParams.params1;
var paramEmployeeID = 1;
//Here it doesn't wait for the onSuccess method from the service which will deliver the object.
$scope.employee = EmployeeService.get(paramEmployeeID);
//$scope.employee = angular.copy(EmployeeService.get(paramEmployeeID));
console.log($scope.employee);
});
The error comes when the page loads and starts with the service and then controller. That's why it tries to load first the employee then it doesn't wait for the onSuccess method and it jumps to the controller to continue and finally comes back to the service to execute the onSuccess method which executes too late because it returns the object but in the controller I already got the undefined object. How can I solve this problem?
Async issue. You can chain the promise. Try:
On the service make sure you return the promise:
this.get = function(id){
var method = "GET";
var url = "http://localhost:8080/rest/employee/get/" + id;
console.log(url);
function onSuccess(response){
console.log('got it');
return response.data;
}
return $http({
method : method,
url : url,
headers: {'Content-Type' : 'application/json'}
}).then(onSuccess, onError);
}
In the controller you can chain it to get the data that you need:
EmployeeService.get(paramEmployeeID).then(function(employee){
$scope.employee = employee;
console.log($scope.employee);
});

Categories