Http, get response from server with rxjs and angular2 - http

I don't know what I am doing wrong, I don't get any response from the server to work using Http. I added the project as plunker if someone could have a deeper look.
https://plnkr.co/edit/3HybQY3vcsCImbuFCWrP?p=preview
post.service.ts
getPosts(){
return this._http.get("http://jsonplaceholder.typicode.com/posts")
.map(res => res.json());
}
app.component.ts
constructor(private _postService: PostService) {
_postService.getPosts()
.subscribe(res => console.log(res));
}

You are making cross-domain request
You need to add some staff to http request header:
Access-Control-Allow-Origin: *
More details: How to create cross-domain request (Angular 2)?

Wasn't anything wrong, worked when restarted my lite server.

There are two major mistakes in your code that's your code is not running as expected.
you are using Http request response but you have not configure #angular/http setting in your config file so you have to add this in the file.
'#angular/http': {
main: 'bundles/http.umd.js',
defaultExtension: 'js'
},
You are trying to get request over http which angular2 won't allow so you have to change your url like
http://jsonplaceholder.typicode.com/posts
to
https://jsonplaceholder.typicode.com/posts
here is your working code demo
Working Example

Related

multisite Wordpress API CORS issue with headers set in theme (v5)

I have a React app which calls a Wordpress v5 API.
const api = `${WAPI}`;
const headers = {
'Content-Type': 'application/json'
} ;
fetch(api, {
headers: headers
})
.then(function(data){
console.log(data);
})
.then(this.handleposts)
.catch(err => console.log(err));
}
Which returns this error in my development tools' console:
Access to fetch at 'http://XXX.XXX.XXX.XX/firstcivdivcareers/wp-json/wp/v2/posts/' from origin 'http://localhost:9000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request.
I used to call a single Wordpress site API but now it doesn't' work. I assumed Wordpress API would work with cross-origin domain calls to be used as a third-party service.
I added changes to the theme's functions.php. When I go to my site in the browser and check the header's in dev tool console. I can see I sent my response with the proper headers. However, doesn't work the same when I call through my JS's fetch call.
Changes added to functions.php:
/**
* Only allow GET requests
*/
function add_cors_http_header(){
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET");
header("Access-Control-Allow-Headers: origin");
}
Locate the file in your wordpress code which is serving the API.
You just have to add at the start of that file:
<? header("Access-Control-Allow-Origin: *"); ?>
Edit:
Instead of editing the core files, the better option is to use the filter as explained in this thread. You can put the following code in your functions.php
add_filter('init', 'add_cors_header');
function add_cors_header() {
header(...);
}
I had this issue as well with my Vue.js code. This is what I added to my GET request and I have had no further issues: https://cors-anywhere.herokuapp.com and it immediately precedes the URL:
let url = 'https://cors-anywhere.herokuapp.com/https://jobs.github.com/positions.json?&markdown=true&page=1';
I hope that helps!
You can use this MS Edge plugin t quickly disable Cors.
CORS Unblock - Microsoft Edge Addons
It will work just fine :)

How to make a "simple" GET request if the resource doesn't allow CORS?

I'm trying to use W3C's CSS Validator Web Service API in a Chrome new tab extension. The docs claim that a request is a simple HTTP GET call to a URI, so I figured this should work:
fetch('http://jigsaw.w3.org/css-validator/validator?uri=http%3A%2F%2Fwww.w3.org%2F&profile=css3&output=json')
.then((response) => {
// do stuff with response
});
Unfortunately the promise fails and I get a message like:
Failed to load. No 'Access-Control-Allow-Origin' header is present on
the requested resource. Origin is therefore not allowed access.
How am I supposed to make a "simple" GET request if the resource doesn't allow CORS?
Thanks!
2017-10-22 Update: The change for adding CORS support to the CSS Validator was merged and pushed to production, so the following now works as-is:
const validatorURL = 'https://jigsaw.w3.org/css-validator/validator' +
'?uri=http%3A%2F%2Fwww.w3.org%2F&profile=css3&output=json';
fetch(validatorURL)
.then(response => response.json())
.then(results => console.log(results))
Original answer:
The CSS Validator doesn’t send the necessary CORS response headers. To fix that, I’ve raised a pull request with a change against the CSS Validator sources that’ll enable your code snippet to work as-is. I’ll post an update here once the change is merged and pushed to production.
In the meantime, you can work around the issue by making your request through a CORS proxy:
const proxyURL = 'https://cors-anywhere.herokuapp.com/';
const validatorURL = 'http://jigsaw.w3.org/css-validator/validator' +
'?uri=http%3A%2F%2Fwww.w3.org%2F&profile=css3&output=json';
fetch(proxyURL + validatorURL)
.then(response => response.json())
.then(results => console.log(results))
For details abou why that works, see the How to use a CORS proxy to get around “No Access-Control-Allow-Origin header” problems section of the answer at No 'Access-Control-Allow-Origin' header is present on the requested resource—when trying to get data from a REST API.
You need to register the allowed origin for the extension's manifest:
"permissions": [
"http://jigsaw.w3.org/"
],
And you might need to set the origin mode for the fetch function as well:
fetch(
'http://jigsaw.w3.org/css-validator/validator?uri=http%3A%2F%2Fwww.w3.org%2F&profile=css3&output=json',
{mode: 'no-cors'})
.then((response) => {
// do stuff with response
});
From chrome web store you can add CORS Filter extension. just enable the filter before you run your code.
From here you can add the filter to your chrome browser.

How do I access nginx header variables in meteor

In my nginx config I've got proxy_pass set to my meteor app. I'm also setting some header variables using proxy_set_header. How do I get access to these variables in my meteor app?
In my main.js on the server I've tried a ton of things in Meteor.onConnection(), but haven't been able to see the values of the variables set by nginx.
Thanks.
You might be able to get the values from the headers for http requests with Webapp.connectHandlers or Webapp.rawConnectHandlers
// server/main.js
Meteor.startup(() => {
WebApp.rawConnectHandlers.use(function(req, res, next) {
console.log(req.headers);
next();
});
}

Accept post request with iron router

I'm trying to accept a post request from my twilio account to my application to get an xml response back. How do I respond to an incoming post request in iron router? I have read the docs and tried everything in there but I just get (Error: Not implemented on server yet). I have tried putting it on the server, on the client and in lib.:
Router (lib/router.coffee)
Router.route('/api/twilio/voice', where: 'server')
.post -> console.log 'hey'
This is due to having this.subscribe then .wait()s configured for both server and client. Look for .wait within your Router configuration scopes and make sure it only runs at the client.
Look at the code part where this happens at the iron-controller repo:
https://github.com/EventedMind/iron-controller/blob/devel/lib/controller_server.js
Also I think a better way to debug (instead of console.log) is to actually use this.response:
Router.route('/api/twilio/voice', { where: server })
.post(function() {
this.response.end('hey');
});
or even the classic format:
Router.route('/api/twilio/voice', { where: server })
.post(function(req, res, next) {
res.end('hey');
});
Edit: Issue filed here and PR here.

Meteor Modify Boilerplate Response with Iron Router

Using Iron Router I can add a route such as /index returns "INDEX CONTENT" from the server:
this.route('index', {
path: '/',
where: 'server',
action: function () {
this.response.end("INDEX CONTENT");
}
});
The default behaviour for a Meteor app is to return a boilerplate HTML file on the initial request to the server which contains the js/css etc required to run the web app.
What I would like to do, however, is place a string (ie "INDEX CONTENT" as above) within the boilerplate which would normally be returned by default if I hadn't added the route. To do this, I'd need to be able to modify a boilerplate response before it is sent to the client but after it is constructed by the standard meteor response mechanism.
Can anyone recommend a way to be able to do this?
You could try the inject-initial meteorite package.
From the docs:
Inject.rawModHtml(id, func). At injection time, calls func(html, res) with the full page HTML which it expects to be returned, in full, after modification. res is the current http connection response request.
I think you would use it like this.
Inject.rawModHtml('breakEverything', function(html) {
return "INDEX CONTENT";
});

Resources