【问题标题】:I need to fetch API to get a raw value from response same as the result in POSTMAN but fail?我需要获取 API 以从响应中获取与 POSTMAN 中的结果相同但失败的原始值?
【发布时间】:2020-04-30 07:33:27
【问题描述】:

我是新来的。只是遇到了一些从前端(反应)获取数据到 JSON 中的原始值的问题。对于登录部分,当我输入电子邮件和密码时,据说响应与 POSTMAN 中的结果相同,但我得到了错误。我花了将近一个星期才弄清楚这个问题。对于那些帮助我解决这个问题的人,我将不胜感激。我将在下面进一步详细说明我的情况:

这是来自邮递员的 API 响应(我应该得到这个响应):

我在浏览器中得到的结果:

源代码:

constructor (props){
  super(props);
  this.state ={
    loginEmail: '',
    loginPassword: ''
  }
  this.login = this.login.bind(this);
  this.onChange = this.onChange.bind(this);
}

login(){
  PostData('api/users/login', this.state).then ((result) => {
    let responseJSON = result;
    console.log(responseJSON);
  });
}

邮政数据:

export function PostData(type, userData = {}){

    let BaseUrl = "https://ems-unimas-58134.herokuapp.com/"

    return new Promise((resolve, reject) => {

        fetch(BaseUrl+type,{
            method: "POST",
            body: JSON.stringify(userData),
            Accept: 'application/json',
            // headers:{
            //   'Content-Type': 'application/json'
            // }
          }).then(res => res.json())
        .then((responseJson) => {
            resolve(responseJson);
        })
        .catch((error)=>{
            console.error('Error:', error);
        })

    });

}

如果你们中的任何人需要更多代码,请在此处点赞。

【问题讨论】:

  • 取消注释 headers 属性。您可以通过单击“标题”选项卡来查看邮递员正在使用哪些标题
  • 嗨,@AngelSalazar 感谢您在这里发表评论。但是,如果我取消注释标题,则会出现此错误“访问从源 'localhost:3000' 获取'ems-unimas-58134.herokuapp.com/api/users/login' 已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:否'访问-Control-Allow-Origin' 标头存在于请求的资源上。如果不透明的响应满足您的需求,请将请求的模式设置为 'no-cors' 以获取禁用 CORS 的资源。"
  • 在邮递员中,您可以将脚本复制为 fetch can you see this
  • @kokoka 那么问题出在您的服务器上,您必须将 localhost 列入白名单

标签: json reactjs api npm fetch


【解决方案1】:

问题是您需要允许 CORS。 你可以在here阅读更多关于CORS的信息

【讨论】:

    猜你喜欢
    • 2017-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多