【发布时间】:2020-01-12 15:42:08
【问题描述】:
它可以执行 GET OK,但无法执行 POST。我已经尝试了各种 Header 组合。它到本地主机。
这是我的 Reactjs 应用调用
export function saveStaff(data) {
return fetch(baseUrl, {
mode: "no-cors",
method: "POST",
headers: {
Host: "localhost:44370",
Allow: "GET, POST",
Accept: "application/json, text/plain",
"Content-Type": "application/json"
},
body: { Name: "tuesday", Department: "tuesday", visitorcount: 0 } // data // JSON.stringify(data)
})
.then(handleResponse)
.catch(handleError);
}
这是来自 Postman 的标题!
POST /api/StaffNamesAPI HTTP/1.1
Host: localhost:44370
Allow: GET, POST
Content-Type: application/json
Accept: application/json, text/plain
User-Agent: PostmanRuntime/7.16.3
Cache-Control: no-cache
Postman-Token: a5b282c7-24e7-46a6-ba22-4f74a31fa9bd,2232ec6c-b3e9-4e29-88e3-abf63675486c
Host: localhost:44370
Accept-Encoding: gzip, deflate
Content-Length: 122
Connection: keep-alive
cache-control: no-cache
{"Name": "Wednesday TestWithPostman",
"Department": "Groan",
"visitorcount": 0 }
这里是 API 控制器
[HttpPost]
[Consumes("application/json")] //https://github.com/aspnet/AspNetCore/issues/4396
public async Task<ActionResult<StaffNames>> PostStaffNames(StaffNames staffNames)
{
_context.StaffNames.Add(staffNames);
await _context.SaveChangesAsync();
return CreatedAtAction("GetStaffNames", new { id = staffNames.Id }, staffNames);
}
现阶段我的课很简单
public class StaffNames
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
public string Department { get; set; }
public int VisitorCount { get; set; }
}
在我的 startup.cs 中,我设置了 CORS
//https://docs.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-2.2#ecors
services.AddCors(options =>
{
options.AddPolicy(MyAllowSpecificOrigins,
builder =>
{
builder.WithOrigins("http://localhost:3000/",
"http://www.contoso.com")
.AllowAnyHeader()
.AllowAnyMethod();
});
});
这是我的 useCors
app.UseCors(MyAllowSpecificOrigins);
//https://stackoverflow.com/questions/52896068/reactasp-net-core-no-access-control-allow-origin-header-is-present-on-the-r
app.UseCors(builder => builder
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials());
感谢您的帮助,我已经考虑了好几个小时了!
【问题讨论】:
-
嗨大卫,没有引号我收到一个错误第 40 行:解析错误:意外的令牌,预期的“,”
-
我猜原因是将已发布的 JSON 反序列化为
StaffNames数据类型的问题。很高兴看到StaffNames类定义更加确定... -
@netchicken 很高兴您使用我在回答中建议的解决方案解决了问题。您看到了吗?如果您没有问题,您可以接受答案吗?
标签: reactjs asp.net-core fetch asp.net-core-webapi