I don't understand why my axios post request isn't working - 404 not found

ScaryBelles picture ScaryBelles · Oct 31, 2017 · Viewed 18.6k times · Source
import React, {Component} from 'react';
import axios from 'axios';

export default class CreateDog extends Component {
    constructor(props){
        super(props)

        this.state = {

            name: '',
            activityLevel: '',
            description: ''
        }
        this.newDog = this.newDog.bind(this)
    }

newDog() {

    var doggy = {
        name: this.state.name,
        activityLevel: this.state.activityLevel,
        description: this.state.description
    }

     axios.post('http://localhost:3002/api/createdog', doggy)
        .then(response => {
            console.log("sent successfully")
        })
    }

render(){
    return(
        <div>
            <div>
                <textarea type="text" placeholder="dog breed name" onChange={(e) => this.setState({name: e.target.value})}> </textarea>
                <textarea type="text" placeholder="dog breed activity level" onChange={(e) => this.setState({activityLevel: e.target.value})}> </textarea>
                <textarea type="text" placeholder="dog breed description" onChange={(e) => this.setState({description: e.target.value})}></textarea>
            </div>

            <div>
                <button onClick={() => this.newDog()}></button>
            </div>
        </div>
    )

}

I have an axios post request in the newDog function.

Here is my endpoint in node with the massive connection string.

massive(config.dblink).then(db => {
    app.set('db', db)
})
app.post('/api/createdog', dc.createDog);

controller:

module.exports = {
createDog: (req, res) => {
    const {name, activityLevel, description} = req.body;

    req.app.get('db').create_dog([name, activityLevel, description])
        .then(dog => {
            console.log(dog)
            res.status(200).send(dog);
        }).catch(err => {
              res.status(500).send(err)})
    }
}

SQL query

INSERT INTO dogBreed (name, activity_level, description)
VALUES
('English Bulldog', 'super lazy', 'English bulldogs are super lazy but 
adorable')
returning *;

I have been looking at this for days and it appears to match all of the examples I am trying to follow. Please help. Sorry for the code overload.

Here is the error I am getting:

POST http://localhost:3002/api/createdog 404 (Not Found)

Answer

Klevin Doda picture Klevin Doda · Aug 14, 2018

I believe the error is because you are using the full URL in this call:

axios.post('http://localhost:3002/api/createdog', doggy)

Instead try using a relative path:

axios.post('/api/createdog', doggy)

If this doesn't work don't forget to add the project name before /api:

axios.post('/projectName/api/createdog', doggy)

This solved it for me.