简体   繁体   English

通过获取Reactjs POST请求

[英]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. 嗨,我正在尝试通过获取操作reactjs POST请求,但遇到两个错误,我经历了所有文档,但错误未解决。

Errors: 错误:

  1. Failed to load http://localhost:8083/students : Response for preflight has invalid HTTP status code 403 无法加载http:// localhost:8083 / students :预检响应具有无效的HTTP状态代码403
  2. Uncaught (in promise) TypeError: Failed to fetch 未捕获(按承诺)TypeError:无法获取

Here is my Reactjs code: 这是我的Reactjs代码:

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. 错误: Response for preflight has invalid HTTP status code 403表示您无权将数据发布到服务器。 This security policy is called as CORS ( https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS ). 该安全策略称为CORS( https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS )。

Here you must have an API server. 在这里,您必须具有API服务器。 The server must allow requests from localhost:8083. 服务器必须允许来自localhost:8083的请求。

To allow such requests, you can add headers to apache configuration files: 要允许此类请求,您可以将头添加到apache配置文件中:

I use following configuration in my apache config file: 我在我的apache配置文件中使用以下配置:

 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: 编辑:要添加,请打开您的apache配置文件并添加以上行:

<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. 配置文件的路径是: /etc/apache2/sites-available/000-default.conf ,这可能与您的情况有所不同。

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) 1- Response for preflight has invalid HTTP status code 403 ,这意味着您需要在标头中发送授权令牌(已将其注释掉)

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. 2- Uncaught (in promise) TypeError: Failed to fetch意味着服务器未发送JSON格式的Respose,然后response.json()引发异常。

I can see you use FormData , with Content-Type header application/json which is wrong. 我可以看到您将FormDataContent-Type标头application/json使用是错误的。

var data = new FormData();

Another point to raise here is you can't set JSON inside FormData like this. 这里要提出的另一点是,您不能像这样在FormData设置JSON

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. 仅在需要将文件发送到服务器时才使用multipart FormData If you do so, make sure you remove the Content-Type header from your request. 如果这样做,请确保从请求中删除 Content-Type标头。

Or else, if you want to send JSON data create a proper JSON payload and send it instead of FormData . 否则,如果要发送JSON数据,请创建一个适当的JSON有效负载并发送它而不是FormData That should work. 那应该工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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