【问题标题】:Angular - bypass the requests through the serverAngular - 通过服务器绕过请求
【发布时间】:2018-06-27 02:28:03
【问题描述】:

提到牛津词典api(https://developer.oxforddictionaries.com)不支持CORS。相反,他们建议让查询到达用户的服务器端应用程序,然后将API请求从用户服务器发送到牛津服务器而不是直接从客户端。所以不可能直接向他们的服务器发送 API 请求。那么,我需要在我的代码中进行哪些更改才能从他们的 api 获取数据。此外,我不想使用代理配置或 CORS 插件或浏览器调整。因为它们会导致安全漏洞,也不能用作永久解决方案。

xyz.service.ts

import { Injectable } from '@angular/core';
import { HttpErrorResponse } from "@angular/common/http";
import {Http, Response} from '@angular/http';
import { HttpHeaders, HttpClient, HttpParams } from '@angular/common/http';
import { Observable } from 'rxjs';
import { catchError } from 'rxjs/operators';



@Injectable({
  providedIn: 'root'
})
 export class XyzService {

   word: String = "aardvark";
   constructor(private _http: HttpClient) {}
   private handleError(err: HttpErrorResponse) {
   console.log(err.message);
   return Observable.throw(err.message);
   }
  getDictonaryData(name?): any {
      if(name){
      this.word = name
  }

  let headers = new HttpHeaders();
  headers.append('Accept','application/json');
  headers.append('app_id','4eb****91');
  headers.append('app_key','7d0740a128***9bbc66907835843d6f');

let myResponse = this._http.get('https://od- 
api.oxforddictionaries.com/api/v1/entries/en/'+this.word,{headers: headers
  });
 return myResponse;

 } 
}

app.component.ts

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { XyzService } from './xyz.service';
import { HttpClient } from '@angular/common/http';
import { catchError } from 'rxjs/operators';

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
 name:string;
 dictData:any;


constructor(private _route: ActivatedRoute, private router: Router, private 
xyzService: XyzService, ) {}

getData() {
  this.xyzService.getDictonaryData(this.name).subscribe(
    data => {

        this.dictData = data;
          console.log(this.dictData);
          } ,

      error => {
          console.log("some error occured");
          console.log(error.errorMessage);
      }
  );

 }}

app.component.html

 <input id="name" type="text" [(ngModel)]="name"/>
 <button (click)="getData()"> Get Data </button>

 <div class="row" *ngIf="dictData">
 <h2>{{dictData["results"][0]["lexicalEntries"][0]["entries"][0]["senses"][0] 
["definitions"]}}

</h2>
</div>

【问题讨论】:

  • 您需要创建自己的 server 端方法(nodejs、php、任何服务器语言),该方法将从远程 url 获取数据。然后在该服务器端方法上实现 CORS(如果需要)

标签: angular


【解决方案1】:

对于节点服务器

步骤 - 1:安装 url

npm install url

步骤 - 2:保存脚本


脚本.js

var https = require('https');
var http = require('http');
var url = require('url');

var my_app_id;
var my_app_key;
var mainRes;

// Recieve get request from client
http.createServer(function (req, res) {

  res.writeHead(200, {'Content-Type': 'text/plain'});

  mainRes = res;
  var parsedUrl = url.parse(req.url, true); // true to get query as object
  var params = parsedUrl.pathname;

  my_app_id = JSON.stringify(req.headers.app_id).replace(/\"/g, "");
  my_app_key = JSON.stringify(req.headers.app_key).replace(/\"/g, "");
  var word_id = params.substring(1);

  if (word_id && my_app_id && my_app_key) {
    // Proper Request
    var options = {
            host: 'od-api.oxforddictionaries.com',
            port: 443,
            path: '/api/v1/entries/en/'+word_id,
        method: 'GET',
        headers: {
            'app_key' : my_app_key,
            'app_id' : my_app_id
        }
    }; 
    console.log("Start");
    var x = https.request(options,function(res){
        console.log("Connected");
        var responseString = "";
        res.on('data',function(data){
            responseString += data;
        });
        res.on("end", function () {
            console.log(responseString); 
            mainRes.end(responseString);
            // print to console when response ends
        });
    });

    x.end();
  } else {
    res.end("Request not proper");
  }

}).listen(1337, '127.0.0.1');

步骤 - 3:运行它

node script.js

第 4 步:发送带有标头的 Get 请求

示例:对于“你好”这个词 获取请求应该是http://yourdomain.com:1337/hellohttp://yourserverip:1337/hello 带有标题 app_id 和 app_key

【讨论】:

    猜你喜欢
    • 2021-05-02
    • 2012-12-30
    • 2019-03-28
    • 1970-01-01
    • 1970-01-01
    • 2010-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多