【发布时间】:2019-02-19 11:56:40
【问题描述】:
我正在使用 react 构建一个网站(它在 localhost:3000 上运行),它从我构建的在 localhost:4000 上运行的 API 获取其用户信息。为了允许两者之间的请求,我被告知使用 npm cors 包来允许来回跨域请求。我在我的 API 中设置了 cors,如下所示:
app.use(cors({credentials: true, origin: true}));
在我的 react 应用程序中,我一直在使用 axios 来发送 get 和 post 请求,我在一个确实收到响应的组件中有一个这样的 get 请求:
isLoggedIn(){
let isLogged = false;
Fetch("http://localhost:4000/IsLogged")
.then((results)=> {
console.log(results)
isLogged = results.data
})
.catch((err) => console.log(err))
this.setState({loggedIn: isLogged})
}
componentDidMount(){
this.isLoggedIn();
}
但是,当我尝试使用此代码接收用户详细信息时:
getUserDetails(){
Fetch("http://localhost:4000/userDetails")
.then((results)=> {console.log(results)})
.catch((err) => console.log(err))
}
componentDidMount(){
this.getUserDetails()
}
我在控制台中得到这个响应:
Access to XMLHttpRequest at 'http://localhost:3000/login' (redirected from 'http://localhost:4000/userDetails') from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
这是服务器端代码:
app.get("/userDetails",(req,res)=>{
//if there is no userID associated with the session then the user hasnt logged in, redirect to login
console.log(req.session.UserID)
if(!req.session.UserID) {
res.redirect("http://localhost:3000/login")
}else{
let userID = req.session.UserID
connection.query("SELECT * FROM `users` WHERE id =" + userID)
.then((rows) => res.send(rows[0]))
.catch((err) => console.error(err))
}
})
这可能是一些愚蠢的事情,所以如果这真的很基本,我很抱歉,任何关于此的阅读链接也会很棒。感谢您提供的任何帮助!
【问题讨论】:
-
为什么错误消息说,“在
http://localhost:3000/login(重定向自http://localhost:4000/userDetails)” - 您在端口 4000 上运行的 API 将重定向到前端的业务在端口 3000 上以…开头? -
它只是检查您是否尝试在未登录的情况下访问用户仪表板,如果您输入
localhost:4000/userDetails,则重定向到登录页面 -
你说这是一个 API,为什么有人会尝试通过调用 API URL 来访问用户仪表板?如果您的任何
:4000URL 在没有正确凭据的情况下被调用,您的 API 应该通过发出适当的错误代码来处理它,而不是通过重定向到 前端!你在这里以一种毫无意义的方式混合了两种不同的东西。
标签: javascript reactjs axios