Ajax POST传递数据时出现问题
发布于 9 年前 作者 RickyDan 3714 次浏览 最后一次编辑是 8 年前 来自 问答

server的代码如下

var fs = require('fs');
var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');

var app = express();
app.set('port',(process.env.PORT || 3000));
app.use('/',express.static(path.join(__dirname,'build')));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.get('/api/comments',function(req,res){
    fs.readFile('comments.json',function(err,data){
        res.setHeader('Cache-Control','no-cache');
        res.json(JSON.parse(data));
    });
});
app.post('/api/comments',function(req,res){
    fs.readFile('comments.json',function(err,data){
        var comments = JSON.parse(data);
        comments.push(req.body);
        fs.writeFile('comments.json',JSON.stringfy(comments,null,4),function(err){
            res.setHeader('Cache-Control','no-cache');
            res.json(comments);
        });
    });
});
app.listen(app.get('port'),function(){
    console.log('server has started: http://localhost: ' + app.get('port') + '/');
});

项目的入口文件如下

var React = require('react');
var CommentBox = require('./components/CommentBox');
React.render(
    <CommentBox url="comments.json" pollInterval={2000} />,
    document.getElementById('content')
);

CommentBox的代码如下

var React = require('react');
var CommentList = require('./CommentList');
var CommentForm = require('./CommentForm');
var $ = require('expose?$!expose?jQuery!jquery');
var CommentBox = React.createClass({
    loadCommentsFromServer: function(){
        $.ajax({
            url: this.props.url,
            dataType: 'json',
            success: function(data){
                this.setState({data: data});
            }.bind(this),
            error: function(xhr,status,err){
                console.log(this.props.url,status,err.toString());
            }.bind(this)
        });     
    },
    handleCommentSubmit: function(comment){
        var comments = this.state.data;
        var newComments = comments.concat([comment]);
        this.setState({data: newComments});
        $.ajax({
            url: this.props.url,
            dataType: 'json',
            type: 'POST',
            data: comment,
            success: function(data){
                this.setState({data: data});
            }.bind(this),
            error: function(xhr,status,err){
                console.error(this.props.url,status,err.toString());
            }.bind(this)
        });
    },

    getInitialState: function(){
        return {data: []};
    },
    componentDidMount: function(){
        this.loadCommentsFromServer();
        setInterval(this.loadCommentsFromServer,this.props.pollInterval);
    },
    render: function(){
        return(
            <div className="commentBox">
              <h1>Comments</h1>
              <CommentList data={this.state.data} />
              <CommentForm onCommentSubmit={this.handleCommentSubmit} />
            </div>           
        );
    }
});
module.exports = CommentBox;

CommentForm的代码如下

var React = require('react');
var CommentForm = React.createClass({
    handleSubmit: function(e){
        e.preventDefault();
        var author = React.findDOMNode(this.refs.author).value.trim();
        var text = React.findDOMNode(this.refs.text).value.trim();
        if(!text || !author){            
            return;
        }
        this.props.onCommentSubmit({author: author, text: text});
        React.findDOMNode(this.refs.author).value = '';
        React.findDOMNode(this.refs.text).value = '';
    },
    render: function(){
        return(
            <form className="commentForm" onSubmit={this.handleSubmit}>
              <input type="text" placeholder="Your name" ref="author" />
              <input type="text" placeholder="Say something..." ref="text" />
              <input type="submit" value="Post" />
           </form>
        );
    }
});
module.exports = CommentForm;

CommentList的代码如下

var React = require('react');
var Comment = require('./Comment');

var CommentList = React.createClass({
    render: function(){
        var commentNodes = this.props.data.map(function(comment){
            return (
                <Comment author={comment.author}>{comment.text}</Comment>
            );
        });
        return(       
            <div className="commentList">
              {commentNodes}
            </div>
        );
});

module.exports = CommentList;

使用webpack打包成功之后,能够跑起来,get方法也能实时获取数据更新状态,但是post方法传递数据的时候,浏览器报了404错误,说 comments.json没有找到,貌似是无法通过post方法去更新comments.json的数据!求大神解答

回到顶部