简体   繁体   中英

Reactjs POST request through fetch

Hi i am trying reactjs POST request through fetch but getting two error's, I went through all docs but error is not solved.

Errors:

  1. Failed to load http://localhost:8083/students : Response for preflight has invalid HTTP status code 403
  2. Uncaught (in promise) TypeError: Failed to fetch

Here is my Reactjs code:

import React from 'react';
import RaisedButton from 'material-ui/RaisedButton';
import TextField from 'material-ui/TextField';
import axios from 'axios';
const style = {
 margin: 15,
marginLeft: 600
};
export default class  Register extends React.Component {
 constructor(props) {
   super(props);
   this.onSubmit=this.handleSubmit.bind(this);
}


handleSubmit(e) {
   e.preventDefault();
   var self = this;
   var data = new FormData();
   const payload = {
   id: 111,
   studentName: 'param',
   age: 24,
   emailId: 2
};
data.append("myjsonkey", JSON.stringify(payload));

fetch('http://localhost:8083/students',{
   method: 'POST',
   body: data,
   headers: {
    // 'Authorization': `bearer ${token}`,
    'Content-Type': 'application/json'
  }
 })
   .then(function(response) {
       return response.json()
     }).then(function(body) {
       console.log(body);
     });
 }

render() {
   return (
     <form onSubmit={this.onSubmit}>
     <div style={style}>
     <TextField ref='id'
     hintText="Enter Student id"
     floatingLabelText="id"
     />
     <br/>
     <TextField ref='sname'
     hintText="Enter your Last Name"
     floatingLabelText="StudentName"
     />
     <br/>
     <TextField ref='age'
     hintText="Enter your Age"
     floatingLabelText="age"
     />
     <br/>

     <TextField ref='emailId'
     hintText="Enter your Email"
     floatingLabelText="emailId"
     />
     <br/>
     <br/>
     <input type="submit" />


     </div>
         </form>


   );
 }


}

Even though here my form values also hard-coded.

The error: Response for preflight has invalid HTTP status code 403 means you don't have access to post data to the server. This security policy is called as CORS ( https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS ).

Here you must have an API server. The server must allow requests from localhost:8083.

To allow such requests, you can add headers to apache configuration files:

I use following configuration in my apache config file:

 Header add Access-Control-Allow-Origin "http://localhost:8083"
    Header add Access-Control-Allow-Headers "Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method,X-Requested-By, Access-Control-Request-Headers,withCredentials"
    Header add Access-Control-Allow-Methods "GET,HEAD,PUT,POST,DELETE,PATCH,OPTIONS"
   Header add Access-Control-Allow-Credentials 'true'

Edit: To add open your apache configuration file and add the above lines:

<VirtualHost *:80>
    ......
    ......
    ......
    Header add Access-Control-Allow-Origin "http://localhost:8080"
    Header add Access-Control-Allow-Headers "Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method,X-Requested-By, Access-Control-Request-Headers,withCredentials"
    Header add Access-Control-Allow-Methods "GET,HEAD,PUT,POST,DELETE,PATCH,OPTIONS"
   Header add Access-Control-Allow-Credentials 'true'
</VirtualHost>

The path for the configuration file is: /etc/apache2/sites-available/000-default.conf , which might be different in your case.

1- Response for preflight has invalid HTTP status code 403 , means that you need to send the authorization token in header (it's commented out)

2- Uncaught (in promise) TypeError: Failed to fetch means the the server is not sending a respose with JSON format then response.json() is throwing an exception.

I can see you use FormData , with Content-Type header application/json which is wrong.

var data = new FormData();

Another point to raise here is you can't set JSON inside FormData like this.

data.append("myjsonkey", JSON.stringify(payload));

Firstly what kind of payload do you need to send. Use multipart FormData only if you need to send files to the server. If you do so, make sure you remove the Content-Type header from your request.

Or else, if you want to send JSON data create a proper JSON payload and send it instead of FormData . That should work.

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