JSONP and AngularJS - javascript

I'm developing software to integrate into a router, like the rest of our stack it's developed using AngularJS, the router manufacturer has an API built into the router which returns JSON(P?).
To be a pain, they've prefixed the JSON response with
while(1);
Then commented out the JSON response, within the (minified) code they've written it is using this, so there is a way to access the data.
Whenever I try (using ngResource) it's just running the while(1); function and causing the browser to crash.
HTTP Response:
while(1); /*[{"username":"admin",
"userlevel":2,
"promptinfo":"",
"enableprompt":false,
"ID":"InternetGatewayDevice.UserInterface.X_Web.UserInfo.1.",
"FirstLogin":1}]*/

Can you use http.get instead ? Meaning is the call made to the same domain that you run it on ? If so, you could parse out the response for anything before and and the [] ?

Related

How to REST call Angular TypeScript Server with JavaScript

I am currently working on a Sessions Server for a company project.
My problem is, I cant find any help to accomplish, that I can do javascript HTTP calls from a javascript server running with http.createServer() and server.listen(8080, ...) to my Angular Server, which is hosted with ng serve running on localhost:4200.
What I want, respectively need,is something like mentioned below in pseudocode:
In my Angular TypeScript file I need something like:
private listdata = new Array<string>();
ngOnInit(){}
constructor(private http: HttpClient){
this.http.listen(method: "POST", address: "http://localhost:4200/data", callback: => (data){
this.listdata = data;}
)
}
So that my Angular Application (Server) can receive REST calls from another Server.
In my JavaScript file I want to do smth. like:
http.post("localhost:4200/data", data, httpOptions);
So in the end, my javascript server running on localhost:8080 sends data to my angular server running on localhost:4200.
I tried to read me through several sources, containing HttpInterceptors etc. but couldnt find a simple solution for Noobs like me.
Is there an easy way, so that my automatically builded and hosted Angular Server can define routes it listens to and process the data directly for frontend use?
Thanks in advance :)
I think you have to read documentation again
In my opinion or am using like that when calling rest.
2.1 Rest function have to write in httpService.service.ts
2.2 Rest I used to HttpInterceptor to login OAUTH it will check auth guards,
then token expired you check easy way.
3. last question: You asking like roles something, you want to show components different users? yes you can manage routing,
https://www.thirdrocktechkno.com/blog/how-to-integrate-interceptor-in-angular-9/

More generic question about receiving a stream with JavaScript

I have a more generic question about receiving a stream with JavaScript
Given the generic use case: I want to get data from backend (csv file, ...) to frontend.
Given the following restrictions:
Backend just accepts 'POST' (non negotiable)
Frontend uses 'Axios' (could be adjusted)
How would I do that?
All the examples in the network work with stream to get data like csv etc., I'm convinced that that's the way to go but couldn't explain it.
My situation
So far I tried a lot to make it work, I did actually but I don't think it was really "Streaming".
Backend: I pushed my stream into the OutputStream of the response and returned the stream. That means the data is visible in the devTools which shoudn't be. Without that, just returning the stream and not writing it to the OutputStream, I always got an "Network error", the backend returned successfully (I guess) but still I got the error.
Frontend: After some time I assume I realized why I got probably got the "Network error": Axios does not support stream
Furthermore I use a fileDownloader that simulates a download click to download the response (POST fetch with Axios) which I formatted into a Blob.
What is necessary to make streaming work? Is there an agenda?
I don't want to fabricate stupid stuff and go somewhere I shouldn't go. That's why I would like to get some information from people who have already some experience with that.
Do I need 'GET' to make streaming work? Or does it work with 'POST' too?
In the backend returning the stream without writing it to the output of the response body is enough?
Is Streaming the right way?
What do I use? Frontend: React, TypeScript, Axios | Backend: C#

React ES6 App - Local API calls

I can't for the life of me figure this out, it seems like it should be straight forward but it's just not clicking.
I have an ES6 app that I created using create-react-app. I've got all the templates and layouts set up for the project and came to trying to pull in data from an API that I want to sit inside the app - like a botched MVC where React handles the views and I run the models and controllers in PHP.
So I have a function in one of my components that I want to fetch some data. I use the fetch() function (I know this isn't yet compatible with a number of browsers but that's a problem for another day) to fetch a relative path from the component to the model I want to load, however the fetch function treats my path as a call to the base URL followed by the request. So with the site running on localhost:3000, I run the following code in my getData() function...
let test = fetch('../models/overall-stats.php').then(function(response) {
console.log(response);
return response;
});
...the URL that fetch hits is then http://localhost:3000/models/overall-stats.php which simply resolves back to the index.html file and loads the app, rather than the PHP file I'm requesting.
If I need to hit that PHP file to get my data, am I wrong in using fetch? Or am I just using it incorrectly? If I shouldn't be using fetch what's a better approach to this problem I'm having?
When I run this on an apache server (after building and deploying) I can get the fetches to work fine (apache recognizes the structure of the URL and hits it as I am expecting) and I hit the file no issues, but I need to be able to work in a local development environment and have the same functionality. The app will end up being deployed live on an apache server.
Any help would be greatly appreciated.
I knew after sleeping on this it would be very straight-forward... I simply had to move my models and controllers into the public directory for them to be accessible. I'll be putting in authentication to the models so that they can't be hit directly, but only through GET requests.
Why don't you just use something like ${baseUrl}/models/... ?
Also for solving browsers problem with fetch you can import the Polyfill or simply use axios (my choice)!
Maybe you can try to use ajax to get or post the data from server, just like this:
$.ajax({
url: '../models/overall-stats.php',
data: {
},
type: 'GET',
dataType : 'json',
success : function(res){
let obj = parseJSON(res)
}
})
or add this on top in your php file because the CORS :
header('Access-Control-Allow-Origin: *');

VueJs 2, NodeJs and reload page

I have a question with VueJs and the refreshing page. When I refresh my VueJs app with specific URL (for example : /tag/1), an error occurs : "Uncaught SyntaxError: Unexpected token <".
My server is created with NodeJs and I use ExpressJs. My templating engine is EJS.
I have defined a route :
app.get('*', (request, response) => {
response.render('layouts/index')
})
In the documentation for ExpressJs, it's possible to use a plugin "connect-history-api-fallback" to replace ".htaccess" of Apache but this cannot work.
let app = express()
app.use(history({
verbose: true,
index: '/'
}))
What is the issue ?
Thanks,
This is happening because your client app (vue.js) is expecting to receive some valid JSON object, but your server is giving a HTML page.
When attempting to convert some string like <html><head>... into a javascript object, your JSON parser fails and gives that error. To replicate this locally, open your developer console and run the following command:
JSON.parse("<html></html>")
To find out what exactly is going wrong, you need to look into the network tab of developer console and look at the server responses for API requests - you expect JSON but server might be serving index.html
Assuming your server side is all good and handles API requests as expected, then it might be a simple error in your vue component - instead of loading your tag data from /api/tag/1 (which gets a valid JSON string), you might be attempting to load /tag/1 (which will only get your index.html).

Can't get Angular $resource to send proper Headers

I'm building a prototype Angular app, using Parse as a temporary RESTful back end (Until the real restful backend is completed)
I've setup a Factory with $resource() but I'm constantly getting a 401 unauthorized.
Right now my factory looks like this (APPIDKEY AND APIKEY are redacted of course)
app.factory('eventFactory', ['$resource', function($resource){
return $resource('https://api.parse.com/1/classes/Events',{},
{headers:{"X-Parse-Application-Id": "APPIDKEY",
"X-Parse-REST-API-Key": "APIKEY"}});
}
]);
I've also tried writing the $resrouce like this.
$resource('https://myAppID:javascript-key=myJavaScriptKey#api.parse.com/1/classes/Events');
But that also returns a 401. however if I copy and paste that URL into my browser the screen prints out all the objects in the request.
I've done extensive googling and read the $resource docs many times but I still can't quite figure this out. I'm thinking it has to do with Cross-Origin policy but the parse documentation says
'For Javascript usage, the Parse Cloud supports cross-origin resource sharing, so that you can use these headers in conjunction with XMLHttpRequest.' So I'm kinda stumped.
Any help is much appreciated. Thanks!
Adding these two lines inside my module.config function fixed it.
$httpProvider.defaults.headers.common['X-Parse-Application-Id']="APPIDKEY"
$httpProvider.defaults.headers.common['X-Parse-REST-API-Key']="RESTAPIKEY"
where APPIDKEY and RESTAPIKEY equal the keys provided from Parse.com

Categories