axios.post似乎不起作用?

时间:2017-12-08 03:38:55

标签: node.js reactjs http-post axios

也许我只是没有正确使用axios,但我现在有一个反应前端和node.js后端。

我正在尝试POST到我的api端点" / api /:id / addItem"但在提出请求时没有记录任何内容。

这是我的代码:

ListForm组件 - >

import React from 'react';
import * as helpers from '../helpers';

class ListForm extends React.Component {
  state = {
    value: ''
  }

  handSubmit = e => {
    e.preventDefault();
    helpers.addItem(this.props.currentUser.googleId, this.state.value);

    this.setState({value: ''});
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <input type="text"
          value={this.state.value}
          onChange={e => this.setState({value: e.target.value})}
        />
        <button>Add item</button>
      </form>
    );
  }
}

export default ListForm;

路线 - &gt;

const mongoose = require('mongoose');
const User = require('../models/userSchema');

module.exports = (app) => {
  app.post('/api/:id/addItem', (req, res) => {
    console.log('HEY!');
  });
};

helpers.js - &gt;

import axios from 'axios';

export const fetchUser = async () => {
  const resp = await axios.get('/api/current_user');

  return resp.data;
}

export const addItem = async (id, newItem) => {
  const resp = await axios.post("/api/" + id + "/addItem", newItem);

  return resp.data;
}

Package.json显示转发请求 - &gt;

{
  "name": "client",
  "version": "0.1.0",
  "private": true,
  "proxy": {
    "/auth/google": {
      "target": "http://localhost:5000"
    },
    "/api/*": {
      "target": "http://localhost:5000"
    }
  },
  "dependencies": {
    "axios": "^0.17.1",
    "react": "^16.2.0",
    "react-dom": "^16.2.0",
    "react-scripts": "1.0.17"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject"
  }
}

1 个答案:

答案 0 :(得分:2)

此处的问题是newItem,而不是json只是简单value

axios.post("/api/" + id + "/addItem", newItem);

应该是这样的:

axios.post("/api/" + id + "/addItem", {value : newItem});

或者从addItem传递json:

helpers.addItem(this.props.currentUser.googleId, this_should_be_json );