Reputation: 4998
I'm aware that this is one of the most common problem. But unfortunately after doing a lot of study about CORS
from the internet and questions on stackoverflow I'm not able to solve it. I'm trying to create a simple Angular project with twitter API. I want to fetch all my timeline status on the webpage with the twitter-api. Here's my code:
server.js
const express = require('express');
const Twitter = require('twit');
const app = express();
const cors = require('cors');
const bodyParser = require('body-parser');
app.listen(3000, () => console.log('Server running'));
app.use(bodyParser.json());
app.use(cors());
const api_client = new Twitter({
consumer_key: 'mykey',
consumer_secret: 'mykey',
access_token: 'mykey',
access_token_secret: 'mykey'
})
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Methods", "GET, PUT, POST");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
app.get('/home_timeline', (req, res) => {
const params = { tweet_mode: 'extended', count: 10 };
api_client
.get('statuses/home_timeline', params)
.then(timeline => {
res.send(timeline);
})
.catch(error => {
res.send(error);
});
});
This is my service twitterservice.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { map } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class TwitterserviceService {
api_url = 'https:/localhost:3000';
constructor(private http: HttpClient) { }
getTimeline() {
return this.http
.get<any[]>(this.api_url+'/home_timeline')
.pipe(map(data => data));
}
}
and this is the component which is using the service twitter-timeline.component.ts
import { Component, OnInit } from '@angular/core';
import { TwitterserviceService } from '../twitterservice.service';
@Component({
selector: 'app-twitter-timeline',
templateUrl: './twitter-timeline.component.html',
styleUrls: ['./twitter-timeline.component.scss']
})
export class TwitterTimelineComponent implements OnInit {
myTimeline: any;
constructor(private api: TwitterserviceService) { }
ngOnInit() {
this.getTwitterTimeline();
}
getTwitterTimeline(): void {
this.api.getTimeline()
.subscribe(
myTimeline => {
this.myTimeline = myTimeline;
console.log(this.myTimeline);
}
)
}
}
On Postman
I'm getting exactly what I want:
But the browser is telling a different story:
I tried disabling the security settings and I also added an extension CORS everywhere
but I think that's not a good idea. I'm getting this for both Chrome and Firefox. Please correct me.
Please correct me where I'm wrong.
Upvotes: 0
Views: 3659
Reputation: 440
I think the problem is that you're making a https request in your angular app. Try using http://url in your service component instead.
Upvotes: 1