提问者:小点点

CORS与nodejs和react一起发布


祝你们大家日安。我正在尝试建立一个登录,现在我正在努力处理注册表单,我使用react js作为前端,使用NodeJS/Express作为后端。

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

null

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;

null

这是来自服务器端的:

null

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
})
});

null

第33行:fetch(url,{

这是第一个代码,前面


共3个答案

匿名用户

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

并且只需执行以下操作:

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

匿名用户

在面对CORS问题时,请记住这些概念,

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

null

    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));

匿名用户

如果将access-control-allow-credentials设置为true表示您允许凭据请求

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

则不能将Access-Control-Allow-Origin设置为*(通配符)

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

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

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