【问题标题】:cors error fetching from react app to localhost express server [duplicate]从反应应用程序获取到本地主机快速服务器的cors错误[重复]
【发布时间】:2019-07-30 00:18:58
【问题描述】:

我的 react 应用在 localhost:3000 上运行

我的 express 服务器在 localhost:1234 上运行

这是我的快递服务器:

const express = require("express")
const cors = require("cors")
const app = express();
const PORT = 1234;
const spawn = require("child_process").spawn;

app.use(cors())

app.listen(PORT,  function(){
console.log(`listening on port:${PORT}...`)
})

app.get("/api/play/:choice", function(req,res){
    res.status(200).send("lets go")
    /*pythonProcess = spawn('python',["./script.py", req.params.choice]);
    pythonProcess.stdout.on('data', function(data) {
    res.status(200).send(data.toString('utf-8'))})*/
})

我有一个这样的反应应用程序获取

fetch(`localhost:1234/api/play/${this.state.value}`)
.then(function(res) {
  res.text().then(function(text){
    console.log(text)
  });
})

我在反应服务器的控制台中收到此错误:

Fetch API cannot load localhost:1234/api/play/rock. URL scheme must be "http" or "https" for CORS request.

当我使用邮递员时,我使用邮递员时,我会得到正确的响应:

http://localhost:1234/api/play/whatever

【问题讨论】:

    标签: express cors fetch


    【解决方案1】:

    在您的 .env 文件中(如果有)(根目录)

    API_URL = http://localhost:1234
    

    并使用它

    const HOSTNAME = process.env.PFPLUS_API_URL;
    fetch(`${HOSTNAME}/api/play/${this.state.value}`)
    .then(function(res) {
      res.text().then(function(text){
        console.log(text)
      });
    })
    

    如果你不通过 env 文件方式就使用这种方式

    fetch(`http://localhost:1234/api/play/${this.state.value}`)
    

    如果显示新的 cors 错误,请在您的 express 服务器文件上使用此代码

    app.all('*', function(req, res, next) {
      res.header('Access-Control-Allow-Origin', '*');
      res.header('Access-Control-Allow-Credentials', 'true');
      res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
      res.header(
        'Access-Control-Allow-Headers',
        'Origin, X-Requested-With, Content-Type, Accept, Authorization'
      );
      next();
    });
    

    【讨论】:

      猜你喜欢
      • 2020-08-25
      • 1970-01-01
      • 2019-10-24
      • 2021-10-17
      • 1970-01-01
      • 1970-01-01
      • 2021-07-26
      • 2020-11-20
      • 2015-10-21
      相关资源
      最近更新 更多