从Angular7到Codeigniter的Http请求::如何发送API密钥,获取“ {”状态”:false,“错误”:“无效的API密钥“}”响应

时间:2019-04-20 07:24:10

标签: rest httprequest codeigniter-3 angular7

我正在从角度服务向codeigniter控制器发出HTTP请求,但没有收到CORS错误,因为我已在控制器的构造函数中添加了以下代码

header('Access-Control-Allow-Origin: *');
        header("Access-Control-Allow-Headers: X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method");
        header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");
        $method = $_SERVER['REQUEST_METHOD'];
        if($method == "OPTIONS") {
            die();
        }

还使用以下代码在尖角根文件夹中创建了proxy.conf.json文件和package.json文件。

{
    "/api": {
        "target": "http://localhost:80/ecommerce/",
        "secure": false,
        "pathRewrite": {
            "^/api": ""
        },
        "changeOrigin": true
    }
}

每当我从service.ts发出请求时,我都会收到{“ status”:false,“ error”:“无效的API密钥”}

const httpOptions = {
  headers: new HttpHeaders({
    'X-API-KEY': 'shwpalensuFJLLVxnX6Su3akdngarsng'
  })
};
@Injectable({
  providedIn: 'root'
})
export class UserService {
  userUrl = 'http://localhost:80/newProject/'; //URL to web api
  constructor(private http: HttpClient){}


  /** GET User-List from the server */
  getUsers (): Observable<User[]> {
    return this.http.get<User[]>(`${this.userUrl}api/User/geUser`);
  }
}

我已经从我的component.ts中调用了此服务

import { User } from './user';
import { UserService } from './user.service'

@Component({
  selector: 'app-content',
  templateUrl: './content.component.html',
  providers: [ UserService ],
  styleUrls: ['./content.component.css']
})
export class ContentComponent implements OnInit {

  users: User[]; 
  constructor(private userService: UserService) { }

  ngOnInit() {
    this.userService.getUsers()
      .subscribe(users => this.users = users);
    console.log(this.users);
  }

帮助我知道我错过了什么,错过了什么,以及是否有任何有效的方法来完成此任务。

you can take a look to the error1 you can take a look to the error2

0 个答案:

没有答案