我已经创建了一个Angular服务,它是具有我自己的后端的授权服务。
我需要向后台发送表单数据,reqData={"username":"string","password":"string"}
和一些标准的头文件。
我的登录component.ts
onSignIn(form: NgForm) {
const email = form.value.email;
const password = form.value.password;
const reqData = {
'app_uname': email,
'app_pass': password
};
const response = this.authService.signInUser(reqData);
}
我的authService:
signInUser(reqData){
const headerInfo = new Headers({
'Content-Type': 'text/plain',
'X-TIME-ZONE': '+5.30',
'X-DEVICE-ID': '911422351920594',
'X-APP-VERSION': '45',
'X-APP-CHANNEL-NAME': 'ANDROID',
'X-DEVICE-OS-VERSION': '45',
'X-DEVICE-MODEL': 'ANDROID'
});
const request = this.http.post('http://server-ip/login', reqData, {headers: headerInfo});
request.subscribe(
(response) => console.log('Success' + response),
(error) => console.log('Error' + error)
);
}
我现在正在检查我是否能够发送数据。
我在日志中看到以下错误:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://server-ip/login. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).[Learn More]
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://server-ip/login. (Reason: CORS request did not succeed)
目前,我的Angular应用程序托管在本地,我的后端在另一台计算机上,通过lan进行通信。
如果我在post-man中发送相同的请求,它工作得很好,我将请求数据作为表单数据发送:其中关键字应该是reqData,值应该是JSON。
我在typescript中做错了什么吗?
发布于 2019-04-25 05:40:36
您需要设置CORS。同源策略正在阻止您对服务器的请求。假设您有两台服务器(example.com和example.org)。用户访问example.com。网页无法向example.org发起请求,除非由于同源策略开启了CORS。启用CORS时,将绕过同源策略。
要启用CORS,请添加“Access-Control-Allow-Origin:*”标头。
我猜post-man没有实现同源策略。
发布于 2019-04-25 06:01:27
如果你的api允许CORS,那么你应该在你的angular项目中设置代理,尝试在你的angular项目中创建文件。
proxy.config.json
{
"/your api": {
"target": "http://your sever:port",
"secure": false
},
}
使用命令ng serve --proxy-config=proxy.conf.json
时,请替换ng serve
发布于 2019-04-26 05:42:10
您必须允许cors请求,因为您的客户端和serve部署在不同的域上。因此在服务器上安装cors并允许客户端连接。请参阅:- https://www.baeldung.com/spring-cors
https://stackoverflow.com/questions/55842369
复制相似问题