【问题标题】:axios.post doesn't seem to work?axios.post 似乎不起作用?
【发布时间】:2017-12-08 03:38:55
【问题描述】:

也许我只是没有正确使用 axios,但我目前有一个 react 前端和 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;

路线 ->

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

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

helpers.js ->

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 显示转发请求->

{
  "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"
  }
}

【问题讨论】:

  • 你的函数名为handSubmit,但你调用的是this.handleSubmit
  • 您的服务器只处理/api/addItem 的帖子,所以当您发布/api/:id/addItem 时显然什么都不返回
  • 抱歉,当我只是想确认帖子是否正常工作时,我把它留在了那里。现已更新
  • package.json 表明您将重定向到服务器 http://localhost:5000 中的句柄 /api/*。你检查了吗?

标签: node.js reactjs http-post axios


【解决方案1】:

这里的问题是 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 );

【讨论】:

    猜你喜欢
    • 2016-11-29
    • 2016-02-01
    • 2020-09-23
    • 2010-12-05
    • 2011-06-14
    • 2015-01-10
    • 2016-02-24
    • 2011-01-18
    • 2018-06-20
    相关资源
    最近更新 更多