Angular-通过服务器绕过请求 [英] Angular - bypass the requests through the server

查看:44
本文介绍了Angular-通过服务器绕过请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

It is mentioned that Oxford dictionary api (https://developer.oxforddictionaries.com) does not support CORS .Instead they recommend to make the query reach user's server side application, and then send the API request from the user's server to oxford's server rather than directly from the client. So it's not possible to directly send API requests to their server. So, What changes i need to make in my code in order to fetch the data from their api . Also i don't want to use proxy configuration or CORS plugins or browser tweaks. As they causes security breaches and also cannot be used as a permanent solution .

xyz.service.ts

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

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

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>

推荐答案

对于 Node Server

步骤-1:安装 URL

npm install url

步骤-2:保存脚本


script.js


script.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请求

Step - 4 : Send Get request with headers

示例:对于单词"hello"获取请求应为 http://yourdomain.com:1337/hello http://yourserverip:1337/hello 带有标题app_id和app_key

Example : For word "hello" Get Request should be http://yourdomain.com:1337/hello or http://yourserverip:1337/hello With headers app_id and app_key

这篇关于Angular-通过服务器绕过请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆