axios.get 没有返回数据
axios.get not returning data
我正在使用 React、Express 和护照来管理身份验证流程。
我最近在 Heroku 中将前端和后端分成两个应用程序,并且我正在尝试连接双方(在服务器文件夹中有一个客户端文件夹之前)。在本地测试时,我的后端在登录访问 http://localhost:5000/auth/current_user 后工作,但是当我使用 axios 并从我的 redux 操作调用时,它没有 return 任何响应。
这是我的前端代码:
export const fetchUser = () => async dispatch => {
try {
const res = await axios.get(
process.env.REACT_APP_API_URL + "/auth/current_user"
);
console.log("fetchUser: ", res);
dispatch({ type: FETCH_USER, payload: res.data });
} catch (e) {
if (e.response) {
console.log("fetchUser:", e.response);
}
}
};
当我登录后端查看是否有 session 时,我得到 {}
作为响应。有时,我会随机获取护照信息 { passport: { user: '5da9b04eb086af53103ec4e9' } }
app.get("/auth/current_user", (req, res) => {
console.log(req.session);
res.send(req.user);
});
来自 Chrome 的 Headers 如下(没有任何回应...):
Chrome headers
如果有人能帮助我,那就太好了!
提前致谢!
我终于找到了问题的解决方案...似乎是 CORS 问题。不是很清楚,研究一下。
因此,部分解决方案在这个答案中:
有了这个,cookie 出现在我前端的控制台日志中。为了充分发挥作用,我必须将原始域添加到 cors。
总之,我在服务器端添加到我的index.js:
app.use(
cors({
methods: ["GET", "POST"],
credentials: true,
origin: "http://localhost:3000"
})
);
我的 axios 的这个配置得到:
const config = {
withCredentials: true,
headers: {
"Content-Type": "application/json"
}
};
您可以像这样使用 cors npm,而不是所有这些。
npm install --save cors
var express = require('express');
var cors = require('cors');
var app = express();
app.use(cors());
/* your regular routes go here */
我正在使用 React、Express 和护照来管理身份验证流程。
我最近在 Heroku 中将前端和后端分成两个应用程序,并且我正在尝试连接双方(在服务器文件夹中有一个客户端文件夹之前)。在本地测试时,我的后端在登录访问 http://localhost:5000/auth/current_user 后工作,但是当我使用 axios 并从我的 redux 操作调用时,它没有 return 任何响应。
这是我的前端代码:
export const fetchUser = () => async dispatch => {
try {
const res = await axios.get(
process.env.REACT_APP_API_URL + "/auth/current_user"
);
console.log("fetchUser: ", res);
dispatch({ type: FETCH_USER, payload: res.data });
} catch (e) {
if (e.response) {
console.log("fetchUser:", e.response);
}
}
};
当我登录后端查看是否有 session 时,我得到 {}
作为响应。有时,我会随机获取护照信息 { passport: { user: '5da9b04eb086af53103ec4e9' } }
app.get("/auth/current_user", (req, res) => {
console.log(req.session);
res.send(req.user);
});
来自 Chrome 的 Headers 如下(没有任何回应...): Chrome headers
如果有人能帮助我,那就太好了!
提前致谢!
我终于找到了问题的解决方案...似乎是 CORS 问题。不是很清楚,研究一下。
因此,部分解决方案在这个答案中:
有了这个,cookie 出现在我前端的控制台日志中。为了充分发挥作用,我必须将原始域添加到 cors。
总之,我在服务器端添加到我的index.js:
app.use(
cors({
methods: ["GET", "POST"],
credentials: true,
origin: "http://localhost:3000"
})
);
我的 axios 的这个配置得到:
const config = {
withCredentials: true,
headers: {
"Content-Type": "application/json"
}
};
您可以像这样使用 cors npm,而不是所有这些。
npm install --save cors
var express = require('express');
var cors = require('cors');
var app = express();
app.use(cors());
/* your regular routes go here */