【问题标题】:Cannot make ajaxs call when deploy in heroku在heroku中部署时无法进行ajaxs调用
【发布时间】:2016-10-01 13:08:13
【问题描述】:

我有一个使用 webpack 捆绑的 web 应用程序,我将整个 react/redux 应用程序放在由 nodejs(express-generator) 提供的公共文件中。当我在 localhost/local 环境中运行时,我的应用程序可以工作。但是,当我部署到 heroku 时。我不能打电话。

以下是错误信息:

    bundle.js:19 GET https://glacial-cove-64389.herokuapp.com/users/ 401 (Unauthorized)

Object {err: Error: Request failed with status code 401 at e.exports (https://glacial-cove-64389.herokuapp.co…}
err
:
Error: Request failed with status code 401 at e.exports (https://glacial-cove-64389.herokuapp.com/bundle.js:19:10382) at e.exports (https://glacial-cove-64389.herokuapp.com/bundle.js:26:6821) at XMLHttpRequest._.(anonymous function) (https://glacial-cove-64389.herokuapp.com/bundle.js:19:9464)
__proto__
:
Object

最初我认为它可能是我的 ROOT_URL,所以我更改了它,下面是我的操作文件的示例。

const ROOT_URL = "//glacial-cove-64389.herokuapp.com"
const axiosOption = {headers: { authorization : localStorage.getItem('token')}}

/*Sign in user*/
export function signinUser({ email, password }){
  return function(dispatch){
    axios.post(`${ROOT_URL}/users/signin`, { email, password })
    .then(function(res){
      dispatch({ type: AUTH_USER })
      localStorage.setItem('token', res.data.token);
      browserHistory.push('/users');
    })
    .catch(function(err){
      dispatch(authError('Invalid email or password'))
      console.log({err});
    })
  }
}

所以发生的情况是反应识别登录并将用户推送到正确的路线。但是一旦它到达主页,它就会返回上述错误消息状态码 401。

我遇到的主要问题是当我尝试执行不起作用的 CRUD 时

这是我的仓库:https://github.com/boyboi86/API_basic_random

【问题讨论】:

    标签: ajax node.js reactjs heroku redux


    【解决方案1】:

    我发现了困难的方式..

    如果您打算在使用 express-generator 搭建脚手架时将所有内容都放在公共文件中。将 CORS 放在 Nodejs 中是不够的,因为现在进行调用的 axios(react)也受到 CORS 的影响,并且您必须在 axios 中配置以下内容:

    axios.defaults.headers.post['Access-Control-Allow-Methods'] = 'PATCH, DELETE, POST, GET, OPTIONS';
    

    这是为了确保所有呼叫都被允许。当我查看响应标头时,我意识到了这一点。

    【讨论】:

      猜你喜欢
      • 2019-11-19
      • 2020-07-19
      • 2023-03-27
      • 1970-01-01
      • 2011-02-03
      • 2020-10-22
      • 2016-10-19
      • 2020-07-11
      相关资源
      最近更新 更多