Javascript 只有某些跨源请求使用npm cors()工作

Javascript 只有某些跨源请求使用npm cors()工作,javascript,reactjs,axios,Javascript,Reactjs,Axios,我正在使用react(它运行在localhost:3000上)构建一个网站,该网站从我构建的运行在localhost:4000上的API获取用户信息。为了允许两者之间的请求,我被告知使用NPMCORS包来允许来回的跨源请求。我已在API中设置cors,如下所示: app.use(cors({credentials:true,origin:true})) 在我的react应用程序中,我一直在使用axios发送get和post请求,我在一个确实接收响应的组件中有一个这样的get请求: isLogge

我正在使用react(它运行在localhost:3000上)构建一个网站,该网站从我构建的运行在localhost:4000上的API获取用户信息。为了允许两者之间的请求,我被告知使用NPMCORS包来允许来回的跨源请求。我已在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))
  }
})

这可能是一些愚蠢的事情,所以我很抱歉,如果这真的是基本的,任何关于这方面的阅读链接也会很好。谢谢你的帮助

在您拥有
app.use(cors({credentials:true,origin:true})的文件中尝试添加以下内容:

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});
然后在你的路线上,通过下一个,像这样:

app.get("/userDetails",(req,res,next)=>{
  //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))
  }
})
让我知道它是否有效!
另外,您使用的是哪种服务器端处理?提供,以便我们能更好地帮助您

您可以在节点服务器中使用以下中间件来修改传入请求。只要把这个放在你溃败之前,它就会奏效

app.use(函数(请求、恢复、下一步){
//您希望允许连接的网站
res.setHeader(“访问控制允许原点”,“*”);
//请求您希望允许的方法
res.setHeader(
“访问控制允许方法”,
获取、发布、选项、放置、修补、删除
);
//您希望允许的请求头
res.setHeader(
“访问控制允许标头”,
X-request-With,内容类型
);
//如果您需要网站在发送的请求中包含cookie,请设置为true
//到API(例如,如果您使用会话)
res.setHeader(“访问控制允许凭据”,true);
//传递到中间件的下一层
next();

});这不是
CORS
的事情

您不能从后端重定向。换句话说,如果用户未登录api,则应返回未授权响应。然后在前端,您应该转到登录页面

问题是您的主机正在尝试从后端访问localhost:3000(前端)。cors是为端口4000或后端设置的

 console.log(req.session.UserID)
 if(!req.session.UserID) {
     //Your should return unauthorized response then check the response at the front end react axios response.
       res.json({
         status: 401,
         message: "Action Not Allowed",
         name: "AUTHORIZATION_ERROR"
       });
     //res.redirect("http://localhost:3000/login")
  }else{ ....


getUserDetails(){
Fetch("http://localhost:4000/userDetails")
    .then((results)=> {
        if(results.data.status == 401) {
              // then change the page.
         }
     })
    .catch((err)   => console.log(err))
}

不,我把这些都加进去了,重新启动了服务器,但还是没有运气!您使用的是哪种服务器端处理?我使用的是Express.js,它是我用来处理HTTP的包requests@MiguelCruz伙计,那根本不是cors的问题。是的,我看得出来。你完全正确。我没有注意港口。他只需要用4000而不是3000。但我会留下我的答案,以防任何人有cors问题。我也尝试了你的代码片段,但它没有工作,我感谢你的评论!为什么错误消息会显示“at
http://localhost:3000/login
(从
http://localhost:4000/userDetails
)”-您在端口4000上运行的API将从什么业务开始重定向到端口3000上的前端…?如果您键入
localhost:4000/userDetails
,只需检查您是否试图在未登录的情况下访问用户仪表板,如果您没有,则重定向到登录页面您说这是一个API,为什么会有人试图通过调用API URL来访问用户仪表板?如果您的
:4000
URL中的任何一个在没有正确凭据的情况下被调用,您的API应该通过发出适当的错误代码来处理,而不是重定向到前端!你在这里以一种毫无意义的方式混合了两种不同的东西。