Angular 5 or 6 subscriptions don’t work when using proxy - angular5

I have built a Java Restful API and I want to access it from Angular 5. For development i have angular server running on port 4200 while my backend runs on 8080. I am trying to setup proxy in angular in order to communicate with backend.
So i have created the following proxy.conf.json file:
{
"/**": {
"target": "http://localhost:8080",
"changeOrigin": true,
"secure": false,
"logLevel": "debug"
}
}
Then i run in terminal
ng serve --proxy-conf proxy.conf.json
and i get the message
Proxy created: /** -> http://localhost:8080
[HPM] Subscribed to http-proxy events: [ 'error', 'close' ]
So till now everything is fine.
When i type in browser url for example
http://localhost:4200/incidents/all
everything works fine and i get the response
[{"id":55,"protocolNo":121212222,"date":1525122000000,"isPayed":true,"yliko":"fdasdfasfsaf","makro":"fdsa","anoso":"fdsa","mikro":"fdsafds","symperasma":"dfsdfsadf","klinikesPlirofories":"fsdafds","histo":"dfsadffga","simpliromatikiEkthesi":"fdsadfsdfa","patient":{"id":1,"firstName":"Μιχαήλ","lastName":"Τουτουδάκης","birthday":"1975-08-19","fatherName":"Δημήτριος","telephone":"6948571893","email":"mixtou#gmail.com","sex":true,"city":{"id":1,"name":"Χανιά"}},"doctor":{"id":1,"firstName":"όνομα","lastName":"επίθετο","telephone":"2821074737","email":"papa#papa.com","fatherName":"πατέρας","specialty":{"id":1,"name":"Αγγειοχειρουργική"},"city":{"id":1,"name":"Χανιά"}},"clinic":{"id":1,"name":"Κλινική Τσεπέτη","telephone":"123456789","address":"Παπαναστασίου","email":"test#test.com"},"signingDoctor":{"id":1,"lastName":"Δασκαλάκη","firstName":"Άννα"},"mikroskopikaSymperasma":null,"anosoEkthesi":null,"cancer":true},{"id":56,"protocolNo":11111,"date":1525640400000,"isPayed":false,"yliko":"dfsadfs","makro":"dfsfsdfdsdfsadfsa","anoso":"dfsdfsfdssfafasd","mikro":"dsfdfsadfsadfssdf","symperasma":"σδγσδγσαδγσγσασδγ","klinikesPlirofories":"δδφφγφγαφαγ","histo":"fdsasdfd","simpliromatikiEkthesi":"γαγσαδσγσδγσδαγ","patient":{"id":5,"firstName":"Στέφανος","lastName":"Μαριόλος","birthday":"2018-03-26","fatherName":"","telephone":"4838583845","email":"","sex":true,"city":{"id":2,"name":"Ρέθυμνο"}},"doctor":{"id":3,"firstName":"Χαράλαμπος","lastName":"Πρωτοπαπαδάκης","telephone":"4343454345","email":"","fatherName":"","specialty":{"id":29,"name":"Πνευμονολογία - Φυματιολογία"},"city":{"id":1,"name":"Χανιά"}},"clinic":{"id":1,"name":"Κλινική Τσεπέτη","telephone":"123456789","address":"Παπαναστασίου","email":"test#test.com"},"signingDoctor":{"id":1,"lastName":"Δασκαλάκη","firstName":"Άννα"},"mikroskopikaSymperasma":"γσαγδσασαδγδασγαγσγσ","anosoEkthesi":"φδαφγφγφδσγ","cancer":true}]
However visiting backend end point from angular i get nothing.
For incidents for example i have the following service:
getIncidents(): Observable<Incident[]> {
console.log('getting incidents');
const incidentsUrl = '/incidents/all';
return this.http.get<Incident[]>(incidentsUrl)
.pipe(catchError(ErrorHandler.handleError));
}
Which generates the following error in javascript console:
core.js:1440 ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'push' of undefined
TypeError: Cannot read property 'push' of undefined
At the following line:
this.subscriptions.push(this.incidentsService.getIncidents().subscribe((results) => {
this.comService.sendIncidents(results);
this.spinner.hide();
}));
Which means that this.incidentsService.getIncidents() retturns nothing??
Any Ideas??

I removed the this.subscriptions.push(...) action and everything works fine. Why is this happening when using subscriptions. I need them because onDestroy i call subscription.unsubsribe() to avoid memory leaks.
Note that this happens when using proxy. If i don't use proxy and deploy the project to tomcat everything works ok. I don't get null inside push().
Any Ideas???
The problem was at the declaration of subscriptions. In the beginning it was:
subscriptions: Subscription[];
I changed it to
subscriptions: Subscription[] = [];
and everything worked fine.
subscriptions
wasn't initialized.

Related

NUXT Redirect issue when making a POST request to external API

I have a form that I built in Nuxt. I'm trying to submit it to an external API. The expected response is a JWT token.
async login() {
const res = await this.$axios.$post(`/api/token`, {
username: this.username,
password: this.password
}, this.headers )
console.log(res)
}
Trying to call the API directly gets me a CORS error, so I use proxy settings in my nuxt.confix.js.
...
modules: [
'#nuxtjs/axios',
'#nuxtjs/proxy'
],
axios: {
baseURL: '/',
proxy: true
},
proxy: {
'/api/': { target: 'https://<apiurl>.com/', changeOrigin: true }
},
...
Now when I check the network tab, it shows a 301 redirect, but the data that was sent in the post request gets thrown away, and it makes a get request to the API which returns a 405 error (because it's expecting a POST request with a data and not an empty GET request).
How can I make a POST request to an external API using NUXT? Is this an option at all?
I tried changing changeOrigin: false, and that seems to get rid of the issue, but it throws a 500 server error instead and an npm error that says
ERROR [HPM] Error occurred while proxying request localhost:3000/api/token to https://<apiurl>.com/ [ERR_TLS_CERT_ALTNAME_INVALID] (https://nodejs.org/api/errors.html#errors_common_system_errors)
Thank you
The problem is not how to send api to an external API ... the problem is in the external API it self ... make sure the external API has no credentials required to make any action ...
if you can make a request to https://jsonplaceholder.typicode.com/posts and get results that means there is no problems in your code ... cors erros in most cases are backend issue ... which means .. the backend developer who worked on it should fix it

webpack dev-server: Avoid proxy errors on HTTP errors returned from proxy target

I have a Vue.js project where I have configured a webpack dev-server to proxy all requests to the UI to my backend server. Here is the relevant part of vue.config.js:
devServer: {
contentBase: PATHS.build,
port: 9000,
https: false,
hot: true,
progress: true,
inline: true,
watchContentBase: true,
proxy: {
'^/': {
target: 'http://127.0.0.1:8089',
secure: false
},
}
},
I've noticed that if the HTTP response code from http://127.0.0.1:8089 is anything other than 2xx then the proxy fails with the following error:
Proxy error: Could not proxy request /api/test from localhost:9000 to http://127.0.0.1:8089.
See https://nodejs.org/api/errors.html#errors_common_system_errors for more information (HPE_INVALID_CHUNK_SIZE).
This also causes the HTTP response code from the request to localhost:9000 to be 500 for any error and all the information about what went wrong on the server side is lost. This is problematic as I want to be able to extract information from error responses to display to the user.
I know it's possible to do because I had it working on an older Angular project which I think was using Webpack 3 (am now using Webpack 4). I tried copying all the dev-server config from this project but it just doesn't seem to work here!
EDIT: I was wrong. The Proxy error does not occur on every bad response but only for one of the requests which is a multipart file upload. Still unable to reproduce this in a smaller example to put on github though so struggling to pinpoint the cause.
This error message comes from node_modules/#vue/cli-service/lib/util/prepareProxy.js, which define a onError callback for node-http-proxy;
So I did some experiment, make back-end api generate 400 404 500 response, but I didn't got this error.
After I happen to close back-end api, error arise:
Proxy error: Could not proxy request /hello from localhost:8080 to http://localhost:8081 (ECONNREFUSED).
I search in the doc and find these:
The error event is emitted if the request to the target fail. We do not do any error handling of messages passed between client and proxy, and messages passed between proxy and target, so it is recommended that you listen on errors and handle them
So the onError do not handle error code, is called only when request fail (500 response is still treated as a complete request, connection refuse is not)
Go back to your error message, [HPE_INVALID_CHUNK_SIZE] means bad request to the back-end api. In this issue, it gives an solution: add a keep-alive header:
devServer: {
publicPath: 'http://localhost:9090/front/static-dev/build/',
port: 9090,
proxy: {
'/**': {
target: 'http://localhost:8080',
secure: false,
changeOrigin: true,
headers: {
Connection: 'keep-alive'
}
},
open: true
}
I have finally found the problem, and I apologise, it was a lot more of a specific issue than I originally thought when I wrote the question.
Issue was to do with a request which was proxied to another server using the Spring RestTemplate:
e.g.
#PostMapping("/upload")
public ResponseEntity upload(#RequestParam("file") MultipartFile file)
throws Exception {
String baseUrl = serviceProperties.getAddress();
HttpEntity<MultiValueMap<String, Object>> request = createMultipartRequest(file.getBytes());
return restTemplate.postForEntity(baseUrl + "/api/upload", filterRequest, String.class);
}
The ResponseEntity returning from the rest template proxy contained the header "Connection: close" when the response was anything other than 200 which cause the connection to close and caused this request to fail to return anything which subsequently made the dev-server proxy fail on the UI.
Fixed this by not passing the response headers from the rest template proxy to the response:
#PostMapping("/upload")
public ResponseEntity upload(#RequestParam("file") MultipartFile file)
throws Exception {
String baseUrl = serviceProperties.getAddress();
HttpEntity<MultiValueMap<String, Object>> request = createMultipartRequest(file.getBytes());
ResponseEntity response = restTemplate.postForEntity(baseUrl + "/api/upload", filterRequest, String.class);
return new ResponseEntity<>(response.getBody(), response.getStatusCode());
}

How to serve data for AJAX calls in a Vue.js-CLI project?

I have a Vue.js CLI project working.
It accesses data via AJAX from localhost port 8080 served by Apache.
After I build the project and copy it to a folder served by Apache, it works fine and can access data via AJAX on that server.
However, during development, since the Vue.js CLI website is being served by Node.js which is serving on a different port (8081), I get a cross-site scripting error) and want to avoid cross-site scripting in general.
What is a way that I could emulate the data being provided, e.g. some kind of server script within the Vue.js-CLI project that would serve mock data on port 8081 for the AJAX calls during the development process, and thus avoid all cross-site scripting issues?
Addendum
In my config/index.js file, I added a proxyTable:
dev: {
env: require("./dev.env"),
port: 8081,
autoOpenBrowser: true,
assetsSubDirectory: "static",
assetsPublicPath: "/",
proxyTable: {
"/api": {
target: "http://localhost/data.php",
changeOrigin: true
}
},
And now I make my AJAX call like this:
axios({
method: 'post',
url: '/api',
data: {
smartTaskIdCode: 'activityReport',
yearMonth: '2017-09',
pathRewrite: {
"^/api": ""
}
}
But now I see in my JavaScript console:
Error: Request failed with status code 404
Addendum 2
Apparent axios has a problem with rerouting, so I tried it with vue-resource but this code is showing an error:
var data = {
smartTaskIdCode: 'pageActivityByMonth',
yearMonth: '2017-09'
}
this.$http.post('/api', data).then(response => {
this.pageStatus = 'displaying';
this.activity = response.data['activity'];
console.log(this.activity);
}, response => {
this.pageStatus = 'displaying';
console.log('there was an error');
});
The webpack template has its own documentation, and it has a chapter about API proxying during development:
http://vuejs-templates.github.io/webpack/proxy.html
If you use that, it means that you will request your data from the node server during development (and the node server will proxy< the request to your real backend), and the real backend directly in production, so you will have to use different hostnames in each environment.
For that, you can define an env variable in /config/dev.env.js & /config.prod.env.js

How to use spiderable with a meteor app hosted on modulus.io

I'm trying to make spiderable works on my meteor app hosted on modulus with SSL.
I have Meteor 1.0, iron:router 1.0, spiderable and node package of phantomjs
All is working on localhost. But once I deploy on Modulus, first I had the error
spiderable: phantomjs failed: null
Then, I added the following environment variable in the modulus panel:
METEOR_PKG_SPIDERABLE_PHANTOMJS_ARGS = --ssl-protocol=tlsv1 --ignore-ssl-errors=yes --debug=true
This is still not working and the debug is outputting multiple times (like it's looping over an error) the following message in the modulus console:
2014-12-03T17:01:00 [DEBUG] WebPage - evaluateJavaScript "(function() { return (function () {
if (typeof Meteor === 'undefined'
|| Meteor.status === undefined
|| !Meteor.status().connected) {
return false;
}
if (typeof Package === 'undefined'
|| Package.spiderable === undefined
|| Package.spiderable.Spiderable === undefined
|| !Package.spiderable.Spiderable._initialSubscriptionsStarted) {
return false;
}
Tracker.flush();
return DDP._allSubscriptionsReady();
})(); })()"
2014-12-03T17:01:00 [DEBUG] WebPage - evaluateJavaScript result QVariant(bool, false)
If anyone knows how to solve this or succeeded to deploy a meteor project on modulus.io with SSL and spiderable. Let's me know the good way to do it :)
Thank a lot !
I solved my problem as follows:
I installed phantomjs locally and run the test script available at http://www.meteorpedia.com/read/spiderable/
phantomjs phantomtest.js
This gave me more details about the error: Parse Error.
Then, it was a javascript file that once compiled/minified, rendered an error caused by select2. The js library that was using it was flat-ui.js (http://designmodo.github.io/Flat-UI/).
I discover this by testing many deploys on *.meteor.com and by adding/removing .js file.
I edit the flat-ui.js library to avoid Parsing Error.
I redeployed on both modulus.io and *.meteor.com. All was working fine on *.meteor.com but still didn't work on modulus.io. That let me thinking about an SSL error but I only saw "spiderable: phantomjs failed: null" in the modulus.io logs.
I add the following environment variable in the modulus panel:
METEOR_PKG_SPIDERABLE_PHANTOMJS_ARGS = --debug=true
and it appears that it was a "SSL Handshake error":
[DEBUG] Network - Resource request error: 6 ( "SSL handshake failed" )
I add another option to the METEOR_PKG_SPIDERABLE_PHANTOMJS_ARGS environment variable:
METEOR_PKG_SPIDERABLE_PHANTOMJS_ARGS = --ignore-ssl-errors=yes --debug=true
Now everything is working fine on modulus.io.
To sumup:
solve javascript errors
add METEOR_PKG_SPIDERABLE_PHANTOMJS_ARGS = --ignore-ssl-errors=yes
I hope this will help some dudes,

jQuery .ajax call returning error when accessing Java Spring service via domain name based URL

My application's HTML5, jQuery Mobile frontend talks to Java server (Spring, Hibernate, MySQL). The application works fine on my notebook as well as in QA environment. On QA, I'm accessing the application using the server's IP address.
When I host the application in Live environment (the same server as QA but a different web app in Tomcat) and try to access it using URL with the domain name, $.ajax calls in the application return error.
One of the calls is as follows:
$.ajax({
type : "GET",
url : "http://www.smartcloudlearning.mobi:9080/SmartCloudLearningMobi/rest/resource/getResourceTypes",
cache : false,
async : false,
dataType : 'json',
success : function(rTypes) {
Alert("success!");
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
alert("An error has occurred making the request: " + errorThrown);
}
});
I get the following error in Firefox:
An error has occurred making the request: [Exception... "Component returned failure code: 0x80004005 (NS_ERROR_FAILURE)" nsresult: "0x80004005 (NS_ERROR_FAILURE)" location: "JS frame :: http://www.smartcloudlearning.mobi/js/jquery-1.7.1.min.js :: <TOP_LEVEL> :: line 4" data: no]
I get the following error in Chrome:
An error has occurred making the request: Error: NETWORK_ERR: XMLHttpRequest: Exception 101
In the server log, I see that the requested Spring service was successfully invoked but it looks like the client doesn't receive the data!
If I hit the URL
http://www.smartcloudlearning.mobi:9080/SmartCloudLearningMobi/rest/resource/getResourceTypes
directly in the browser, I get expected results! I sense that this is somehow due to how I forward server request from Apache to Tomcat.
The following are the lines in Apache / httpd server's httpd.conf file:
ProxyPass /SmartCloudLearningMobi http://www.smartcloudlearning.mobi:9080/SmartCloudLearningMobi
ProxyPassReverse /SmartCloudLearningMobi http://www.smartcloudlearning.mobi:9080/SmartCloudLearningMobi
Can anyone tell me what's amiss here? Much appreciated!
I managed to solve the problem:
The browser was giving the error on .ajax call because I had port number in my URL. The port number got carried over when I created 'live' URL from my QA URL. When I removed the port number from the .ajax call's URL, the call started returning success!
Jason Foglia, your statement "... and also the port..." nudged me to explore that angle... thanks a lot!
You're probably getting an error because of a security concept called "same origin policy" which doesn't allow you to call a service from a different domain. Or at least, disallow you from calling a method in that service.
Same discussion is found here - AJAX Cross Domain
You can however implement a cross-domain using JSONP - Wikipedia on JSONP
The solution is to change the datatype to JSONP:
$.ajax({
url:"http://www.smartcloudlearning.mobi:9080/SmartCloudLearningMobi...",
dataType: 'jsonp',
...
});
Try using an relative url:
If that doesn't work is the domain name the same as the url and also the port.
Browsers don't allow cross domains.
$.ajax({
type : "GET",
url : "/SmartCloudLearningMobi/rest/resource/getResourceTypes",
cache : false,
async : false,
contentType : "application/json"
dataType : 'json',
success : function(rTypes) {
Alert("success!);
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
alert("An error has occurred making the request: " + errorThrown);
}
});
The browser was giving the error on .ajax call because I had port number in my URL. The port number got carried over when I created 'live' URL from my QA URL. When I removed the port number from the .ajax call's URL, the call started returning success!
Jason Foglia, your statement "... and also the port..." nudged me to explore that angle... thanks a lot!