react axios GET not working. Log out 'name.toU

2019-07-28 22:35发布

问题:

I've created the most basic react app possible and am trying to do a simple GET request. It throws a TypeError and states, 'name.toUppercase is not a function'. I only have the one function. Any ideas what is causing this or how to debug?

import React, { Component } from 'react';
import axios from 'axios';
import logo from './logo.svg';
import './App.css';

class App extends Component {
    state = {
        order_id: Number,
        order_date: '',
        size: '',
        crust: '',
        toppings: [],
    };

    componentDidMount() {
        return axios
            .get('https://59b6v76zci.execute-api.us-west- 
                                            2.amazonaws.com/nr/example', {
                method: 'GET',
                mode: 'cors',
                headers: 'Access-Control-Allow-Origin',
            })
            .then(response => this.setState({ order_id: response.order_id }))
            .catch(err => console.log('err', err));
    }

    render() {
        return (
            <div className="App">
                <header className="App-header">
                    <img src={logo} className="App-logo" alt="logo" />
                    <h1 className="App-title">Welcome to React</h1>
                </header>
                <p className="App-intro">
                    To get started, edit <code>src/App.js</code> and save to reload.
                </p>
            </div>
        );
    }
}

export default App;

This is the what is returned in the console

    err TypeError: name.toUpperCase is not a function
    at processHeader (normalizeHeaderName.js:7)
    at Object.forEach (utils.js:218)
    at normalizeHeaderName (normalizeHeaderName.js:6)
    at transformRequest (defaults.js:32)
    at transform (transformData.js:16)
    at Object.forEach (utils.js:224)
    at transformData (transformData.js:15)
    at dispatchRequest (dispatchRequest.js:37)
    at <anonymous>

回答1:

Try changing your axios request to this:

axios
    .get('https://59b6v76zci.execute-api.us-west-2.amazonaws.com/nr/example', {
        method: 'GET',
        mode: 'cors',
        headers: { 'Access-Control-Allow-Origin': true },
    })
    .then(response => this.setState({ order_id: response.data.order_id }))
    .catch(err => console.log('err', err));

You got two things wrong - headers should be an object, and the data in the response should be under response.data.

Also, on a side-note, Access-Control-Allow-Origin header usually comes as a response header and not on the request.