【发布时间】:2022-01-19 01:12:03
【问题描述】:
我需要使用 javascript 调用 webapi POST 方法。
该方法接受一个模型。我能够从 POSTMAN 正确调用此方法,并且还可以查看数据库中的条目。
// POST api/values
[HttpPost]
public IHttpActionResult Post([FromBody] Models.InspectionPhoto iPhoto)
{
try
{
Debug.WriteLine("In post method");
var connstr = ConfigurationManager.ConnectionStrings["MyDbConnection"].ConnectionString;
Debug.WriteLine("initializing dbconnection");
var db = new RamDbDataContext(connstr);
Debug.WriteLine("mapping entity");
var inspectionPhoto = new DBLinq.InspectionPhoto
{
InspectionId = iPhoto.InspectionId,
InsertEmployee = iPhoto.Employee,
UpdateEmployee = iPhoto.Employee,
Photo = iPhoto.Data,
InspectionCategoryId = 8,
UpdateDate = DateTime.UtcNow,
InsertDate = DateTime.UtcNow
};
Debug.WriteLine("inserting entity");
db.InspectionPhotos.InsertOnSubmit(inspectionPhoto);
db.SubmitChanges();
Debug.WriteLine("done inserting entity");
int id = inspectionPhoto.Id;
return Ok(id);
}
catch(Exception ex)
{
Debug.WriteLine(ex.Message);
return Ok(-1);
}
}
当我尝试从 javascript 调用此方法时,它没有到达端点。我玩过 CORS 设置,但这并没有多大帮助。
这是我调用此方法的 javascript 代码。
<script>
function callwebapi()
{
jsonIn = document.getElementById("mytext").value;
console.log('++As you are+++');
console.log(jsonIn);
console.log('++As you are+++');
const uri = 'https://localhost:44304/api/values';
fetch(uri, {
method: 'POST',
cache: 'no-cache',
credentials: 'same-origin',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'User-Agent': 'PostmanRuntime/7.28.4'
},
body: jsonIn
})
.then(result => console.log(result.status))
.then(response => response.json())
.then(response => console.log('Success: ', response))
.catch(error => console.error('Failure: ', error));
}
</script>
<textarea id="mytext">
{"Id": -1, "InspectionId": 95, "CategoryId": 9, "Employee": "Roger Moore", "Data": null}
</textarea>
<button onclick="callwebapi();">Click this and send your data!</button>
我在 chrome 浏览器控制台中遇到的错误是
TypeError: 获取失败 在 callwebapi (大约:89:13) 在 HTMLButtonElement.onclick (About:110:37)
我创建了一个 ASP .NET Web 应用程序并开始使用 Web 表单项目。 客户端代码是在 About.cshtml 页面上创建的。
我最终需要将此代码合并到现有应用程序中。 如何修复此错误并成功拨打电话?
编辑: 邮递员电话请求。这就是我从 Postman 拨打电话的方式。
【问题讨论】:
-
您能说明一下您是如何使用 Postman 获得结果的吗?
-
这里没有足够的信息来准确回答,但看起来像might be this。注意:不同的端口算作跨域
-
@Liam cors 问题在此代码的一次迭代中引起了人们的注意。它现在已经消失了,这就是当前的问题。
标签: javascript asp.net-web-api