[英]POST https://accounts.spotify.com/api/token 415 error when using fetch
[英]Error 415 when call POST API using Fetch in ReactJS
我想從 React 中的方法調用一個 API 進行注冊。 下面是我的 javascript 代碼:
fetch('http://localhost:5001/api/Account', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
email: "hugh.daniel@gmail.com",
name: "Hugh Daniel",
password: "1234"
})
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
這是我的控制器
[HttpPost]
public ResponseModel RegisterByEmail([FromBody]UserModel user)
{
return _accountService.RegisterEmail(user);
}
我試圖在我的 javascript 代碼中添加mode: 'no-cors'
,但它使Content-Type
設置為普通。 如果我像這樣使用 Postman 對其進行測試,則該 API 可以正常工作
您首先需要與CORS作戰。 您不能針對不同於開發服務器所服務的domain:port
API請求。 您在項目中使用Webpack嗎? 如果是,最簡單的方法是通過Webpack配置來設置API代理。 參見文檔 。 像這樣:
// webpack.config.js
devServer: {
port: 3030,
proxy: {
'/api': {
target: `http://localhost:5001`,
secure: false
}
}
}
現在,您必須從fetch
地址參數中刪除host:port
,並且還要在請求設置中添加Accept
標頭:
fetch('/api/Account', {
method: 'post',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
// ...
}
)
不要在主體中使用JSON.stringify
發送請求,以下代碼將完成工作。
fetch('http://localhost:5001/api/Account', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: {
email: "hugh.daniel@gmail.com",
name: "Hugh Daniel",
password: "1234"
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
嘗試這個
[ApiController]
[Consumes("application/json")]
[Produces("application/json")]
[Route("[controller]")]
public class TestController : ControllerBase
{}
在js中:
await fetch(this.url, { method: 'POST', cache: 'no-cache', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data) });
來源: https : //pretagteam.com/question/angular-http-post-formdata-unsupported-media-type-from-c-controller
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.