【问题标题】:CORS issue with nodejs and reactnodejs的CORS问题并做出反应
【发布时间】:2021-03-18 00:21:09
【问题描述】:

大家好。我正在尝试建立一个登录,现在我正在努力使用注册表单,我将 react js 用于前端,将 nodejs/express 用于后端。

我创建了注册表单,我将此注册表单中的数据放入一个对象中,将其解析为 JSON obj 并通过 fetch api 将其发送到节点服务器,但是 cors 并没有让这种情况发生,我'不知道为什么。接下来是来自寄存器的代码(前端)

import React, { useState } from 'react';
import './Register.css';
import Title from './Title/Title';
import Label from './Label/Label';
import Input from './Input/Input';


function Register(){

    const [ name, setName ] = useState('');
    const [ lastname, setLastname ] = useState('');
    const [ email, setEmail ] = useState('');
    const [ username, setUsername ] = useState('');
    const [ password, setPassword ] = useState('');

    function handleChange(name, value){
        if(name==='name')setName(value);
        else if (name==='lastname')setLastname(value);
        else if (name==='email')setEmail(value);
        else if (name==='username')setUsername(value);
        else if (name==='password')setPassword(value);
    }


    function handleSubmit(e){
        e.preventDefault();
        let account = { name, lastname, email, username, password };
        if(account)console.log(account);

        var url = 'http://localhost:3030/';
        
        
        fetch(url, {
        method: 'OPTION', 
        body: JSON.stringify(account), 
        headers:{            
            'Content-Type': 'application/json'
        }
        }).then(res => res.json()) 
        .catch(error => console.error('Error:', error))
        .then(response => console.log('Success:', response));
       
        
///////////////////////////////////////////////////////////////////////////////////

    }

    return(
        <div className='register-div'>
             <Title text='Register Form'/>
             <div className='squareout'>

             
            <div className='square'>
            <Label text='Name'/>
            <Input attribute={{type:'text', name:'name'}} handleChange={handleChange}/>
            </div>

            <div className='square'>
           <Label text='Last Name'/>
            <Input attribute={{type:'text', name:'lastname'}} handleChange={handleChange}/>
           </div>

           <div className='square'>
           <Label text='E-Mail'/>
            <Input attribute={{type:'text', name:'email'}} handleChange={handleChange}/>
           </div>
            
           <div className='square'>
           <Label text='Username'/>
            <Input attribute={{type:'text', name:'username'}} handleChange={handleChange}/>
           </div>
            
           <div className='square'>
            <Label text='Password'/>
            <Input attribute={{type:'password', name:'password'}} handleChange={handleChange}/>
            </div>
            
            

            </div>
            <button className='boton' onClick = {handleSubmit}>Register</button>
            
            
        </div>
    )
};

export default Register;

这是来自服务器端:

const express = require('express');
const app = express();
const port = 3030;

app.listen(port, () => {
    console.log(`Example app listening at http://localhost:${port}`)
  })
app.use(express.static('public'));

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

app.use(express.json());
app.post('http://localhost:3030/', (request, response) => {
console.log(request.body);
const data = request.body;
response.json({
  
    name: data.name,
    lastname: data.lastname,
    email: data.email,
    username: data.username,
    password: data.password
})
});

但我收到此错误:

第 33 行:获取(网址,{

这是来自第一个代码,正面

【问题讨论】:

  • 关于 CORS 问题和运行 express 的 node.js 服务器有很多很多 Stack Overflow 问题。您研究了哪些,尝试了哪些答案,为什么它们没有解决您的特定问题?
  • 我在发布之前进行了研究,碰巧我找到的解决方案对我没有帮助,与我的案例无关,对我来说太复杂了,尝试过但没有用..或者是其他东西。我认为在这里引用它们并不重要,也许我错了

标签: node.js reactjs express


【解决方案1】:

您可以使用CORS,而不是重新发明轮子

然后简单地做:

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

【讨论】:

    【解决方案2】:

    只需在遇到 CORS 问题时记住这些概念,

    1. 这不是前端应用程序故障(大部分)
    2. 您正在尝试跨域请求
    3. 默认情况下会被阻止
    4. 您可以通过 allowOrigins 使用后端来允许此操作(语法因语言而异)
    5. 这里的问题是从 localhost:3000 访问 localhost:3030

        const express = require('express');
        const cors = require('cors');
        const app = express();
        app.use(cors())
    
      //for single origin
      var corsOptions = {
      origin: 'http://localhost:8080',
      optionsSuccessStatus: 200 // For legacy browser support
     }
    
    app.use(cors(corsOptions));

    source

    【讨论】:

      【解决方案3】:

      如果您设置Access-Control-Allow-Credentials to true 表示您允许凭据请求

      res.setHeader('Access-Control-Allow-Credentials', true) 
      

      那你不能把Access-Control-Allow-Origin设置成*(wildcard)

      res.setHeader("Access-Control-Allow-Origin", "*");
      

      所以这里的解决方案是, 您必须在此处设置特定的来源,(reactjs 的前端应用程序来源默认为 http://localhost:3000/)

      res.setHeader("Access-Control-Allow-Origin", "http://localhost:3000/");
      

      【讨论】:

        【解决方案4】:

        最后我找到了解决方案,首先我使用“POST”而不是“OPTION”方法,在服务器端,我将“http://localhost:3030/”更改为“/”并正常工作.

        【讨论】:

          猜你喜欢
          • 2021-12-05
          • 2019-07-26
          • 2019-08-07
          • 2020-05-21
          • 1970-01-01
          • 2019-03-01
          • 2021-12-05
          • 2017-08-30
          • 2021-03-29
          相关资源
          最近更新 更多