NodeJS Axios - React Get请求已被CORS策略阻止

pqwbnv8z  于 2023-02-21  发布在  Node.js
关注(0)|答案(1)|浏览(217)

我正在尝试使用Axios获取API(https://www.cryptonator.com/api)以获得响应。
我正在努力解决遇到的这个问题。
我使用Axios进行简单的API调用
文件:api/索引. js

import axios from "axios";

export default axios.create({
   baseURL: "https://api.cryptonator.com"
});

使用axios调用API
文件:测试/索引. js

import axios from "../api";

axios.get("/api/ticker/btc-usd")
     .then((response) => {
      console.log(response.data);
      })
      .catch((e) => {
       console.log(e);
 });

这会引发CORS错误
为了修复CORS错误,我尝试使用以下命令

var express = require('express')
  var cors = require('cors')
  var app = express()
  app.use(cors())

但我收到这个错误后,Uncaught TypeError: Cannot read properties of undefined (reading 'prototype').我不能解决这个错误.
花了很多时间找出解决方案却无济于事。
我的package.json

{
  "name": "crypto-dashboard",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^5.16.5",
    "@testing-library/react": "^13.4.0",
    "@testing-library/user-event": "^13.5.0",
    "@types/cors": "^2.8.13",
    "@types/jest": "^27.5.2",
    "@types/node": "^16.18.12",
    "@types/react": "^18.0.28",
    "@types/react-dom": "^18.0.11",
    "axios": "^1.3.3",
    "cors": "^2.8.5",
    "dotenv": "^16.0.3",
    "express": "^4.18.2",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-scripts": "^4.0.3",
    "web-vitals": "^2.1.4"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "proxy": "http://localhost:3000",
  "devDependencies": {
    "@types/express": "^4.17.17",
    "assert": "^2.0.0",
    "buffer": "^6.0.3",
    "crypto-browserify": "^3.12.0",
    "https-browserify": "^1.0.0",
    "os-browserify": "^0.3.0",
    "process": "^0.11.10",
    "react-app-rewired": "^2.2.1",
    "react-error-overlay": "6.0.9",
    "stream-browserify": "^3.0.0",
    "stream-http": "^3.2.0",
    "ts-loader": "^9.4.2",
    "typescript": "^4.9.5",
    "url": "^0.11.0"
  }
}
mwg9r5ms

mwg9r5ms1#

请在cors中间件中添加cors选项,如

var express = require('express')
  var cors = require('cors')
  var app = express()
  var corsOption = {
    origin: "*", // or you can change it with your frontend url
    optionsSuccessStatus: 200,
  }
  app.use(cors(corsOption))

这将使您能够在不同的源之间进行通信

相关问题