我正在 angularJs
中制作一个页面,当我向 API 发送请求时,会生成错误:
我的代码是:
<!DOCTYPE html>
<html ng-app="AppIndex">
<head>
<meta charset="utf-8">
<title>Hola mundo</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.9/angular.min.js"></script>
<script src="ControllerIndex.js"></script>
</head>
<body ng-controller="ControllerIn">
{{"Hola Mundo" + nombre}}
<button ng-click="metodos()">Enviar</button>
<ul>
<li ng-repeat="response in posts">
<h2>holaaaaa</h2>
<p>{{response.title}}</p>
<p>{{response.body}}</p>
</li>
</ul>
</body>
</html>
和javaScript
angular.module("AppIndex",[])
.controller("ControllerIn", function($scope, $http){
$scope.nombre = "Juan";
$scope.newPost = {};
$scope.responses = [];
$scope.metodos = function(){
$http({
method: 'POST',
url: 'http://localhost:900/Servicios/forgotPassword',
Headers: {"Access-Control-Allow-Origin": "http://127.0.0.1", "Access-Control-Allow-Methods": "POST", "Content-Type" : "application/json"},
data: {"user" : "admin1"}
}).then(function (response){
console.log(response);
$scope.posts = response;
},function (error){
console.log(error);
});
}
})
错误信息是:
POST http://localhost:900/Servicios/forgotPassword 403 {data: "Invalid CORS request", status: 403, config: {…}, statusText: "", headers: ƒ, …
我正在使用AngularJS 1.7.9
最佳答案
Cors 策略是从服务器管理的
您需要允许您的服务器特定(或所有)URL 可以访问您的服务器
允许它的方法是
在您的 Http 响应中添加此 header ,并指定您的网址或星号以允许所有
Access-Control-Allow-Origin, "your url"
Access-Control-Allow-Origin, "*"
您还可以通过添加附加 header 来选择仅允许某些请求方法(或所有类型):
Access-Control-Allow-Methods, "POST"
Access-Control-Allow-Methods, "*"
浏览器首先发送一个预检请求,检查来源和请求类型是否匹配,只有当它看到它像上面的 header 一样允许时,它才会进行实际的调用。
PS cors 问题仅在从浏览器调用时出现,而不是从服务器调用或 postman 等开发工具调用时出现
关于javascript - 无效的 CORS 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59620105/