【问题标题】:400 Bad Request for POST to API for js app, but not asp.net mvc app [duplicate]400 Bad Request for POST to API for js app,但不是asp.net mvc app [重复]
【发布时间】:2019-10-27 13:38:05
【问题描述】:

关于 CORS 的精彩解释 No 'Access-Control-Allow-Origin' header is present on the requested resource—when trying to get data from a REST API

我使用 C# (httpclient) 创建了一个本地 asp.net mvc 应用程序,以 POST 到服务器上的 API,该服务器设置为允许 CORS 并且它可以工作。但我在本地运行的 javascript 应用程序返回以下内容:

从源“http://localhost:3000”访问“https://apiurl/auth/token”处的 XMLHttpRequest 已被 CORS 策略阻止:请求的资源上不存在“Access-Control-Allow-Origin”标头。

GET 请求在 js 应用程序中工作。这是一段sn-p代码:

axios({
  method: 'post',
  headers: {
    Accept: 'application/json',
    'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8'
  },
  baseURL: 'https://apiurl',
  url: '/oauth/token',
  data: {
    grant_type: 'password',
    username: this.state.username,
    password: this.state.password
  }
}).then(resp => {
  console.log(resp);
});

API 是启用了 CORS 的 WEBAPI。

config.EnableCors(new EnableCorsAttribute("*", "*", "*"));

我也了解代理是一种潜在的解决方案,但我很想知道我是否在这里遗漏了什么。

【问题讨论】:

  • 请求响应的HTTP状态码是什么?使用浏览器开发工具中的网络窗格进行检查。是 4xx 还是 5xx 错误而不是 200 OK 成功消息?我猜这可能是 400 Bad Request 错误。
  • 是的,400 错误请求
  • 检查您发送请求的服务器端的服务器日志。查看服务器在那里记录的任何消息,这些消息表明为什么 POST 不起作用,从而导致服务器最终发送 400 响应。您从前端 JavaScript 代码发送的 POST 请求未按照服务器预期的方式格式化 POST 请求。
  • 如果您不发送 JSON,则需要为 Axios 提供正确的数据格式。
  • 好的,让我前进,谢谢你们。我现在得到一个 200,json 需要是查询字符串格式。现在收到提到的相同错误,但出现 200 和以下警告:VM278:1 Cross-Origin Read Blocking (CORB) blocks cross-origin response apirurl/auth/token with MIME type application/json

标签: javascript post asp.net-web-api axios


【解决方案1】:

尝试将Access-Control-Allow-Origin设置为https://apiurl,将withCredentials设置为true

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-29
    • 2023-03-13
    • 1970-01-01
    • 1970-01-01
    • 2015-09-21
    • 2016-05-30
    相关资源
    最近更新 更多