Reactjs 为什么在react JS中使用POST方法获取请求时出现错误415

Reactjs 为什么在react JS中使用POST方法获取请求时出现错误415,reactjs,Reactjs,我正在尝试使用API添加客户。当我运行代码时,我得到了415个类似这样的错误 在浏览器控制台中发布415 Customer.js:71 这是我的密码。我有两个文件,一个是Customer,另一个是AddCustomer,这是表单 客户JS import React from 'react'; import { Table, Button } from 'semantic-ui-react'; import AddCustomer from './AddCustomer'; export def

我正在尝试使用API添加客户。当我运行代码时,我得到了415个类似这样的错误 在浏览器控制台中发布415 Customer.js:71

这是我的密码。我有两个文件,一个是Customer,另一个是AddCustomer,这是表单

客户JS

import React from 'react';
import { Table, Button } from 'semantic-ui-react';
import AddCustomer from './AddCustomer';

export default class Customer extends React.Component {

constructor(props) {
    super(props);
    this.state = {
        error: null,
        isLoaded: false,
        users: []
    }

    this.onAddFormSubmit = this.onAddFormSubmit.bind(this);
}

//fetch data 
componentDidMount() {

    const customerApi = 'https://localhost:44387/api/Customers';

    const myHeader = new Headers();
    myHeader.append('Content-type', 'application/json');
    myHeader.append('Accept', 'application/json');
    myHeader.append('Origin','https://localhost:44387');

    const options = {
        method: 'GET',
        myHeader
    };

    fetch(customerApi, options)
    .then(res => res.json())
    .then(
        (result) => {
            this.setState({
                users: result,
                isLoaded: true
            });
        },
        (error) => {
            this.setState({
                isLoaded: true,
                error
            });
        }
    )


}

onAddFormSubmit(data) {

    const customerApi = 'https://localhost:44387/api/Customers';

    const myHeader = new Headers();

    const options = {
        method: 'POST',
        myHeader: {
            'Accept': 'application/json, text/plain',
            'Content-Type': 'application/json;charset=UTF-8'
        },
        body: {
            "name":"Rahul",
            "address":"102 Hobson Street"
        }
    };

    fetch(customerApi, options)
    .then(res => res.json())
    .then(
        (result) => {
            this.setState({

                user:result
            })
        },(error) => {
            this.setState({ error });
        }
    )
}

render() {
    const { users } = this.state;

    return (
        <div>
            <AddCustomer onAddFormSubmit = {this.onAddFormSubmit}/>
            <h3>hello{JSON.stringify(this.state.fields)}</h3>
            <Table celled textAlign='center'>
                <Table.Header>
                    <Table.Row>
                        <Table.HeaderCell>ID</Table.HeaderCell>
                        <Table.HeaderCell>Name</Table.HeaderCell>
                        <Table.HeaderCell>Address</Table.HeaderCell>
                        <Table.HeaderCell>Action</Table.HeaderCell>
                        <Table.HeaderCell>Action</Table.HeaderCell>
                    </Table.Row>
                </Table.Header>

                <Table.Body >
                    {
                        users.map(user => (
                            <Table.Row key={user.customerId}>

                                <Table.Cell>{user.customerId}</Table.Cell>
                                <Table.Cell>{user.name}</Table.Cell>
                                <Table.Cell>{user.address}.Address</Table.Cell>

                                <Table.Cell>
                                    <Button color='yellow'>Edit</Button>
                                </Table.Cell>

                                <Table.Cell>
                                    <Button color='red'>Delete</Button>
                                </Table.Cell>

                            </Table.Row>
                        ))
                    }
                </Table.Body>

                <Table.Footer>
                    <Table.Row>
                        <Table.HeaderCell colSpan='5'>
                            No of Pages
                    </Table.HeaderCell>
                    </Table.Row>
                </Table.Footer>
            </Table>

        </div>
    )
}

}
import React from 'react';
import { Button, Form, Modal } from 'semantic-ui-react';

export default class Customer extends React.Component {

constructor(props) {
    super(props);

    this.state = {};

    this.initialState = {
        name: '',
        address: ''
    };

    this.state = this.initialState;

    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
}

handleChange(event) {
    const name = event.target.name;
    const value = event.target.value;

    this.setState({
        [name]:value,
    })
}

handleSubmit(event) {
    event.preventDefault();
    this.props.onAddFormSubmit(this.state);
    this.setState(this.initialState);
}

//On cancel button click close Create user form
closeCreateForm = () => {
    this.setState({  })
}

//Open Create new Customer form
openCreateCustomer = () => {
    this.setState({  })
}

render() {

    return (
        <div>
            <Modal closeOnTriggerMouseLeave={false} trigger={
                <Button color='blue' onClick={this.openCreateCustomer}>
                    New Customer
        </Button>
            } open={this.state.showCreateForm}>
                <Modal.Header>
                    Create customer
    </Modal.Header>
                <Modal.Content>
                    <Form onSubmit={this.handleSubmit}>

                        <Form.Field>
                            <label>Name</label>
                            <input type="text" placeholder ='Name' name = "name"
                                value = {this.state.name} 
                                onChange = {this.handleChange}/>
                        </Form.Field>

                        <Form.Field>
                            <label>Address</label>
                            <input type="text" placeholder ='Address' name = "address"
                                value = {this.state.address}
                                onChange = {this.handleChange}/>
                        </Form.Field>
                        <br/>
                        <Button type='submit' floated='right' color='green'>Create</Button>
                        <Button floated='right' onClick={this.closeCreateForm} color='black'>Cancel</Button>
                        <br/>
                    </Form>

                </Modal.Content>
            </Modal>

        </div>
    )
}

}
从“React”导入React;
从“语义ui反应”导入{Table,Button};
从“/AddCustomer”导入AddCustomer;
导出默认类Customer extends React.Component{
建造师(道具){
超级(道具);
此.state={
错误:null,
isLoaded:false,
用户:[]
}
this.onAddFormSubmit=this.onAddFormSubmit.bind(this);
}
//获取数据
componentDidMount(){
常数customerApi=https://localhost:44387/api/Customers';
const myHeader=新的头();
append('Content-type','application/json');
append('Accept','application/json');
myHeader.append('Origin','https://localhost:44387');
常量选项={
方法:“GET”,
我的头
};
获取(customerApi,选项)
.then(res=>res.json())
.那么(
(结果)=>{
这是我的国家({
用户:结果,
isLoaded:正确
});
},
(错误)=>{
这是我的国家({
isLoaded:是的,
错误
});
}
)
}
onAddFormSubmit(数据){
常数customerApi=https://localhost:44387/api/Customers';
const myHeader=新的头();
常量选项={
方法:“POST”,
myHeader:{
“接受”:“application/json,text/plain”,
“内容类型”:“应用程序/json;字符集=UTF-8”
},
正文:{
“名称”:“Rahul”,
“地址”:“霍布森街102号”
}
};
获取(customerApi,选项)
.then(res=>res.json())
.那么(
(结果)=>{
这是我的国家({
用户:结果
})
},(错误)=>{
this.setState({error});
}
)
}
render(){
const{users}=this.state;
返回(
你好{JSON.stringify(this.state.fields)}
身份证件
名称
地址
行动
行动
{
users.map(user=>(
{user.customerId}
{user.name}
{user.address}.address
编辑
删除
))
}
页数
)
}
}
当我打开“添加客户”表单并点击“提交”按钮时,它会在获取时给我错误信息。我做错了什么

AddCustomer JS

import React from 'react';
import { Table, Button } from 'semantic-ui-react';
import AddCustomer from './AddCustomer';

export default class Customer extends React.Component {

constructor(props) {
    super(props);
    this.state = {
        error: null,
        isLoaded: false,
        users: []
    }

    this.onAddFormSubmit = this.onAddFormSubmit.bind(this);
}

//fetch data 
componentDidMount() {

    const customerApi = 'https://localhost:44387/api/Customers';

    const myHeader = new Headers();
    myHeader.append('Content-type', 'application/json');
    myHeader.append('Accept', 'application/json');
    myHeader.append('Origin','https://localhost:44387');

    const options = {
        method: 'GET',
        myHeader
    };

    fetch(customerApi, options)
    .then(res => res.json())
    .then(
        (result) => {
            this.setState({
                users: result,
                isLoaded: true
            });
        },
        (error) => {
            this.setState({
                isLoaded: true,
                error
            });
        }
    )


}

onAddFormSubmit(data) {

    const customerApi = 'https://localhost:44387/api/Customers';

    const myHeader = new Headers();

    const options = {
        method: 'POST',
        myHeader: {
            'Accept': 'application/json, text/plain',
            'Content-Type': 'application/json;charset=UTF-8'
        },
        body: {
            "name":"Rahul",
            "address":"102 Hobson Street"
        }
    };

    fetch(customerApi, options)
    .then(res => res.json())
    .then(
        (result) => {
            this.setState({

                user:result
            })
        },(error) => {
            this.setState({ error });
        }
    )
}

render() {
    const { users } = this.state;

    return (
        <div>
            <AddCustomer onAddFormSubmit = {this.onAddFormSubmit}/>
            <h3>hello{JSON.stringify(this.state.fields)}</h3>
            <Table celled textAlign='center'>
                <Table.Header>
                    <Table.Row>
                        <Table.HeaderCell>ID</Table.HeaderCell>
                        <Table.HeaderCell>Name</Table.HeaderCell>
                        <Table.HeaderCell>Address</Table.HeaderCell>
                        <Table.HeaderCell>Action</Table.HeaderCell>
                        <Table.HeaderCell>Action</Table.HeaderCell>
                    </Table.Row>
                </Table.Header>

                <Table.Body >
                    {
                        users.map(user => (
                            <Table.Row key={user.customerId}>

                                <Table.Cell>{user.customerId}</Table.Cell>
                                <Table.Cell>{user.name}</Table.Cell>
                                <Table.Cell>{user.address}.Address</Table.Cell>

                                <Table.Cell>
                                    <Button color='yellow'>Edit</Button>
                                </Table.Cell>

                                <Table.Cell>
                                    <Button color='red'>Delete</Button>
                                </Table.Cell>

                            </Table.Row>
                        ))
                    }
                </Table.Body>

                <Table.Footer>
                    <Table.Row>
                        <Table.HeaderCell colSpan='5'>
                            No of Pages
                    </Table.HeaderCell>
                    </Table.Row>
                </Table.Footer>
            </Table>

        </div>
    )
}

}
import React from 'react';
import { Button, Form, Modal } from 'semantic-ui-react';

export default class Customer extends React.Component {

constructor(props) {
    super(props);

    this.state = {};

    this.initialState = {
        name: '',
        address: ''
    };

    this.state = this.initialState;

    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
}

handleChange(event) {
    const name = event.target.name;
    const value = event.target.value;

    this.setState({
        [name]:value,
    })
}

handleSubmit(event) {
    event.preventDefault();
    this.props.onAddFormSubmit(this.state);
    this.setState(this.initialState);
}

//On cancel button click close Create user form
closeCreateForm = () => {
    this.setState({  })
}

//Open Create new Customer form
openCreateCustomer = () => {
    this.setState({  })
}

render() {

    return (
        <div>
            <Modal closeOnTriggerMouseLeave={false} trigger={
                <Button color='blue' onClick={this.openCreateCustomer}>
                    New Customer
        </Button>
            } open={this.state.showCreateForm}>
                <Modal.Header>
                    Create customer
    </Modal.Header>
                <Modal.Content>
                    <Form onSubmit={this.handleSubmit}>

                        <Form.Field>
                            <label>Name</label>
                            <input type="text" placeholder ='Name' name = "name"
                                value = {this.state.name} 
                                onChange = {this.handleChange}/>
                        </Form.Field>

                        <Form.Field>
                            <label>Address</label>
                            <input type="text" placeholder ='Address' name = "address"
                                value = {this.state.address}
                                onChange = {this.handleChange}/>
                        </Form.Field>
                        <br/>
                        <Button type='submit' floated='right' color='green'>Create</Button>
                        <Button floated='right' onClick={this.closeCreateForm} color='black'>Cancel</Button>
                        <br/>
                    </Form>

                </Modal.Content>
            </Modal>

        </div>
    )
}

}
从“React”导入React;
从“语义ui反应”导入{按钮、表单、模式};
导出默认类Customer extends React.Component{
建造师(道具){
超级(道具);
this.state={};
this.initialState={
名称:“”,
地址:''
};
this.state=this.initialState;
this.handleChange=this.handleChange.bind(this);
this.handleSubmit=this.handleSubmit.bind(this);
}
手变(活动){
const name=event.target.name;
常量值=event.target.value;
这是我的国家({
[名称]:值,
})
}
handleSubmit(事件){
event.preventDefault();
this.props.onAddFormSubmit(this.state);
this.setState(this.initialState);
}
//在“取消”按钮上,单击“关闭”“创建用户窗体”
closeCreateForm=()=>{
this.setState({})
}
//打开创建新客户表单
openCreateCustomer=()=>{
this.setState({})
}
render(){
返回(
创建客户
名称
地址

创造 取消
) } }
我认为服务器需要不同的内容类型。 我看到您正在调用
.setState({user:result})

但您正在映射状态中的用户[]。 我想你需要做的是


fetch(apiUrl)
  .then(res => this.setState({ users: result}))
  .catch(err => this.setState({error : err}))

错误非常清楚
https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/415
。看看服务器端我对
myHeader
有疑问,它不应该是
header:myHeader
?是的,我在myHeader上遇到了错误。在同一个文件中,我成功地调用了GET请求,但当我尝试调用POST请求时,我总是在onAddFormSubmit(数据)中的同一个like fetch(customerApi,选项)上出错