尝试了很多Thins,但错误持续存在,并且不允许使用相同的错误代码405方法
下面是我的代码。用于auth.service.ts
import { Injectable } from '@angular/core';
import { Http ,Headers, RequestOptions } from '@angular/http';
let apiUrl = " http://wiesoftware.com/greenchili/apisecure/login/";
var headers = new Headers();
headers.append('Access-Control-Allow-Origin' , '*');
headers.append('Access-Control-Allow-Methods', 'POST, GET');
headers.append('Content-Type', 'application/x-www-form-urlencoded');
headers.append('Accept','application/x-www-for-urlencoded');
@Injectable({
providedIn: 'root'
})
export class AuthService {
constructor(public http: Http ) { }
userlogin(value){
return new Promise((resolve,reject) => {
var headers = new Headers();
this.http.post(apiUrl + 'loginUsers', value).subscribe(res => {
resolve(res.json());
}, (err) => {
reject(err);
});
});
}
}
显示错误的结果
General:-
Request URL: http://wiesoftware.com/greenchili/apisecure/login/loginUsers
Request Method: OPTIONS
Status Code: 405 Method Not Allowed
Remote Address: 43.255.154.38:80
Referrer Policy: no-referrer-when-downgrade
Response Header:-
Access-Control-Allow-Headers: content-type
Access-Control-Allow-Methods: GET, PUT, POST, DELETE, HEAD, OPTIONS
Access-Control-Allow-Origin: *
Request Header:-
Provisional headers are shown
Access-Control-Request-Headers: content-type
Access-Control-Request-Method: POST
Origin: http://localhost:8100
Referer: http://localhost:8100/login
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36
(KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36
我希望request方法为POST,但默认情况下始终为OPTIONS。
答案 0 :(得分:0)
您必须创建代理
1。首先在您的package.json附近创建proxy.conf.json
{
"/Your_API/1.0.0": {
"target": "http://wiesoftware.com/greenchili/apisecure/login/",
"changeOrigin": true,
"secure": false,
"logLevel": "debug"
}
}
“服务”:{ “ builder”:“ @ angular-devkit / build-angular:dev-server”, “选项”:{ “ browserTarget”:“ app:build”, “ proxyConfig”:“ proxy.conf.json” }, “配置”:{ “生产”: { “ browserTarget”:“ app:build:production” }, “ ci”:{ “进度”:false } } }
在您的基本路径中
protected basePath = './Your_API/1.0.0';
运行并测试
答案 1 :(得分:0)
我得到了解决我的问题的方法,问题不在前端,而是后端php服务器的问题。 为了解决这个问题,我们必须在api.php文件中的服务器上添加一些代码。 代码如下:-
<?php
//http://stackoverflow.com/questions/18382740/cors-not-working-php
if (isset($_SERVER['HTTP_ORIGIN'])) {
header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Max-Age: 86400'); // cache for 1 day
}
// Access-Control headers are received during OPTIONS requests
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
exit(0);
}
?>