如何使用CORS npm模块

时间:2020-01-04 21:38:13

标签: reactjs express cors

我已经建立了一个非常基本的示例来使cors模块正常工作,以便可以从React前端向Express JS服务器发出axios调用。

反应前端

import React from 'react';
import Axios from 'axios'
import './App.css';
import 'bootstrap/dist/css/bootstrap.css';

function App() {

  const callTest = () =>{
    console.log("test called")
    Axios.get('http://localhost/5000/testCall')
    .then((res) => {
      console.log(res.data)
    })
  }

  return (
    <div className="App">
      <div class="row">
        <div class="col-12">
          <p>Welcome to the CORS test</p>
        </div>
      </div>
      <div class="row">
        <div class="col-12">
          <button onClick={() => callTest()}>Click to run test function</button>
        </div>
      </div>
    </div>
  );
}

export default App;

Express节点服务器

const express = require('express')
const bodyParser = require('body-parser')
const cors = require('cors')

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

const port = 5000

app.get('/testCall', (req,res) =>{
    console.log("test call function has been called!!")
    res.send("Hello from the node server")
})

app.get('/', (req,res) =>{
    console.log("this was called")
})

app.listen(port, (req,res) =>{
    console.log("app is running on port " + port)
})

但是我的浏览器出现以下错误。

跨域请求被阻止:“同源起源”策略不允许读取http://localhost/5000/testCall处的远程资源。 (原因:CORS请求未成功。)

有人对我想念的东西有任何想法吗?

0 个答案:

没有答案
相关问题