简体   繁体   中英

Cross origin requests are only supported for protocol schemes error in react

when i tried to do post method in react with nodejs as backend , it is getting this error , i don't know why, but i think my coding is correct only. please help me to solve this issue.

Failed to load localhost:3000/doctors/register: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.
dispatchXhrRequest @ xhr.js:178
xhrAdapter @ xhr.js:12
dispatchRequest @ dispatchRequest.js:59
Register.js:36 Error: Network Error
    at createError (createError.js:16)
    at XMLHttpRequest.handleError (xhr.js:87)
    at dispatchXhrRequest (xhr.js:178)
    at new Promise (<anonymous>)
    at xhrAdapter (xhr.js:12)
    at dispatchRequest (dispatchRequest.js:59)

in react

import React, { Component } from 'react'
import axios from 'axios';

class Register extends Component {
  constructor() {
    super()
    this.state = {
      name: '',
      gender:'',
      designation:'',
      email: '',
      password: '',
      confirm_password: '',
      hospital_id:'',
      errors: {}
  }
  this.onChange=this.onChange.bind(this);
  this.onSubmit=this.onSubmit.bind(this);
  }
  onChange(e) {
    this.setState({[e.target.name]:e.target.value})
  }
  onSubmit(e) {
    e.preventDefault();
    var resObj ={
      name:this.state.name,
      gender:this.state.gender,
      designation:this.state.designation,
      email:this.state.email,
      password:this.state.password,
      confirm_password:this.state.confirm_password,
      hospital_id:this.state.hospital_id
    }
    axios.post('localhost:3000/doctors/register',resObj)
    .then(res => console.log(res.data))
    .catch(err => console.log(err))
  }
  render() {
    return (
      <div className="register">
        <div className="container">
          <div className="row">
            <div className="col-md-8 m-auto">
              <h1 className="display-4 text-center">Sign Up</h1>
              <p className="lead text-center">Create your account</p>
              <form onSubmit={this.onSubmit}>
                <div className="form-group">
                  <input type="text" className="form-control form-control-lg" placeholder="Name" name="name" value={this.state.name} onChange={this.onChange} />
                </div>
                <div className="form-group">
                  <input type="text" className="form-control form-control-lg" placeholder="Gender" name="gender" value={this.state.gender} onChange={this.onChange} />
                </div>
                <div className="form-group">
                  <input type="text" className="form-control form-control-lg" placeholder="Designation" name="designation" value={this.state.designation} onChange={this.onChange} />
                </div>
                <div className="form-group">
                  <input type="email" className="form-control form-control-lg" placeholder="Email Address" name="email" value={this.state.email} onChange={this.onChange}/>
                </div>
                <div className="form-group">
                  <input type="password" className="form-control form-control-lg" placeholder="Password" name="password" value={this.state.password} onChange={this.onChange} />
                </div>
                <div className="form-group">
                  <input type="password" className="form-control form-control-lg" placeholder="confirm Password" name="confirm_password" value={this.state.password2} onChange={this.onChange} />
                </div>
                <div className="form-group">
                  <input type="text" className="form-control form-control-lg" placeholder="Hospital_id" name="hospital_id" value={this.state.hospital_id} onChange={this.onChange} />
                </div>
                <input type="submit" className="btn btn-info btn-block mt-4" />
              </form>
            </div>
          </div>
        </div>
      </div>
    )
  }
}

export default Register;

You missed the http:// or a simple // before localhost

Using //localhost... should automatically use the current used protocol

Seperate answer as requested - once a proxy has been set up you not longer need to supply a full path and a relative one will work

localhost:3000/doctors/register to /doctors/register

Solution that worked for me was to set headers to after defining app in the NodeJS server main/index/server.js file.

    app.use((req, res, next) => {
     res.set({
       'Access-Control-Allow-Origin': '*',
       'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE',
       'Access-Control-Allow-Headers': 'Content-Type'
     })
     next();
   })

This should fix it.

This is a CORS issue - put a proxy to your API inside your react client package.json

 "proxy": "http://localhost:5000/"

You will also then need to update your URL in your component

Heres a similar post How to create a proxy in React/Webpack to call an external API

A project with REACT and Node CORS issue is solved as

React:

axios.defaults.headers.post['Content-Type'] ='application/x-www-form-urlencoded';
axios.defaults.headers.post['Access-Control-Allow-Origin'] = '*';
axios.post('http://localhost:port/..../add_', obj)
    .then(res => console.log(res.data));

Here 'HTTP://.....' is mandatory. Node:app.js

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM