如何在angular中发布表单数据?
我试图将其中一个表单数据发布到特定的服务器,该服务器已禁用CORS,这意味着它将只接受post方法和dis allowed OPTIONS飞行前请求,这是完全可以理解的,但其中一个帖子说,如果请求是简单请求(post的内容类型为application/x-www-form-urlencoded,)这应该不会造成问题,但我仍然得到错误的 控制台上的实际错误。。 访问位于的XMLHttpRequest “https://*********.com/hpm/launchTransnoxScreen.hpm”来自源代码 “”已被CORS策略阻止:否 “Access Control Allow Origin”标头出现在请求的服务器上 资源 -- 你能帮我确认一下这个问题吗?我对angular完全陌生,刚刚开始探索 已经检查了上面的URL如何在angular中发布表单数据?,angular,cors,angular7,form-data,angular-httpclient,Angular,Cors,Angular7,Form Data,Angular Httpclient,我试图将其中一个表单数据发布到特定的服务器,该服务器已禁用CORS,这意味着它将只接受post方法和dis allowed OPTIONS飞行前请求,这是完全可以理解的,但其中一个帖子说,如果请求是简单请求(post的内容类型为application/x-www-form-urlencoded,)这应该不会造成问题,但我仍然得到错误的 控制台上的实际错误。。 访问位于的XMLHttpRequest “https://*********.com/hpm/launchTransnoxScreen.h
import { Injectable } from '@angular/core';
import { Patient } from '../model/patient';
import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class SignupService {
private url: string = "https://stagemc.transnox.com/hpm/launchTransnoxScreen.hpm";
private httpHeadersVar = {
headers: new HttpHeaders({
'Content-Type': 'application/x-www-form-urlencoded',
'Accept': 'text/html'
})
};
patientFormData: Patient;
constructor(private http: HttpClient) { }
callThP(data) {
const formData = new FormData();
formData.append('myKey1', 'some value 1');
formData.append('myKey2', 'some value 2');
formData.append('myKey3', 'true');
this.http.post(this.url, formData, this.httpHeadersVar).subscribe(
(res) => {
console.log(res);
},
err => console.log(err)
);
}
}
当我们点击按钮时,下面的html示例单独运行良好
它连接到主机并使用示例页还原
<html>
<head></head>
<body>
<form id="hppForm" name="hppForm" method="POST" action=" https://stagecp.transnox.com/hpm/launchTransnoxScreen.hpm">
<input name="uniqueID" id="uniqueID" type="hidden" value="XXX3" />
<input name="deviceID" id="deviceID" type="hidden" value="test_deviceID"/>
<button type="submit" class="btn btn-primary btn-block">Sign up</button>
</form>
</body>
</html>
注册
我认为HTTP头不起作用:试试这个:
`实施这一点:
从'@angular/common/http'导入{HttpClient,HttpHeaders};
常量httpOptions={
标题:新的HttpHeaders({
“内容类型”:“应用程序/json”
})
};
这是http.post
(`Your URL`,formData)。subcribe(
(res)=>{
控制台日志(res);
},
err=>console.log(err)
);代码>您可以点击以下链接:
您还应该检查您创建API的后端语言,在那里启用CORSHi Venkata,实际上它不是API调用。这就是我不使用json头的原因。这是一个简单的html表单提交,如果表单的所有值都正确,那么服务器将重定向到它们自己的页面。请检查我上面提到的示例html。顺便说一句,谢谢你的回复。你用哪种语言制作的api。在api配置中,您必须允许CORSHi Shiv,正如我前面提到的,这应该被视为简单的请求,而不应该发送选项方法。Thanks@DnyaneshwarMuley我相信通过选项
你说的是飞行前。您的意思是HTTP定义的简单请求
,包括内容类型为application/x-www-form-urlencoded
的POST
方法。我认为你的问题完全正确,不应该引发CORS例外。其他人提到了API
。但正如你所知,你所调用的资源是不相关的。浏览器/调用者是实施CORS的人,而不是您正在调用的资源。因此,如果浏览器确定它不是一个简单请求
,它会抛出该异常。尽管如此,我认为问题在于您使用的HTTP包(可能是角度HTTP)。他们可能会添加违反简单请求规则的附加头。我没有文档,但是一个例子可能是类似于Accept Encoding
。但是,我不是简单请求
规则的大师,尽管我很确定这是因为它添加的头违反了规则。