NodeJS React JS -即使在要求CORS之后也会出现CORS错误

koaltpgm  于 2023-10-17  发布在  Node.js
关注(0)|答案(4)|浏览(124)

我用的是Express&ReactJS

快递编码:

const Express = require('express');
const PORT = 5000;
const cors = require('cors');

const server = Express();
server.use(cors());   // I've added the cors

server.get('/users', (req, res) => {
    res.send({"users": [ {"user1": "John"}, {"user2": "Nick"} ]);
})

server.listen(PORT, () => {
console.log("server is running on 5000")
});

React代码:

import { useState,useEffect } from 'react';

const Home = () => {

  async function fetchData() {
      try{
        const output = await fetch(`http://localhost:5000/users`);
        console.log(output);
      } catch(e){
          console.error(e);
      }
     
  }

  useEffect(() => {
        fetchData();
     }, [])
  }

    return (
        <h1>FetchData</h1>
    )

 export default Home;

做了这些事之后...我仍然在我的控制台中得到CORS错误。
以下是完整的错误消息:

Response { type: "cors", url: "http://localhost:5000/users, redirected: false, status: 500, ok: false, statusText: "Internal Server Error", headers: Headers, body: ReadableStream, bodyUsed: false }

在做了一些研究之后,我发现在package.json文件中添加"proxy": "http://localhost:5000"可以解决这个问题。但什么都没发生。
我现在该怎么办?
谢谢您的支持:)

ubbxdtey

ubbxdtey1#

请把这个兑换

server.get('/users', (req, res) => {
    res.send({"users": [ {"user1": "John"}, {"user2": "Nick"} ]);
})

这是:

server.get('/users', (req, res) => {
    res.json({users: [ {"user1": "John"}, {"user2": "Nick"} ]);
})
mdfafbf1

mdfafbf12#

尝试使用axios而不是fetch:

// npm install axios

import { useState,useEffect } from 'react';
import axios from 'axios'

const Home = () => {

  async function fetchData() {
      try{
        const output = await axios(`http://localhost:5000/users`);
        console.log(output);
      } catch(e){
          console.error(e);
      }
     
  }

  useEffect(() => {
        fetchData();
     }, [])
  }

    return (
        <h1>FetchData</h1>
    )

 export default Home;
jfewjypa

jfewjypa3#

尝试使用核心选项,

const corsOptions = {
  origin: ['http://localhost:<port_of_reactapp>'],
  methods: ['GET', 'POST', 'DELETE', 'UPDATE', 'PUT', 'PATCH'],
};
server.use(cors(corsOptions));

https://expressjs.com/en/resources/middleware/cors.html

muk1a3rh

muk1a3rh4#

如果你已经npm安装了cors,在你的const服务器中,将const服务器从const server = Express();更改为const server = express();
https://expressjs.com/en/resources/middleware/cors.html
或者尝试使用node-http-proxy,然后只从本地主机请求:

http.createServer(function(req, res) {proxy.web(req, res, { target: 'http://localhost:5000/users' });});

安装方式:https://github.com/http-party/node-http-proxy

相关问题