对我的mongodb服务器进行api调用的好方法

时间:2015-12-30 17:09:24

标签: javascript node.js mongodb

我设置了mongodb,并使用邮差测试了创建,读取,更新和删除功能。

但是,现在我想基本上从我项目中的其他地方进行http POST。要做到这一点,有什么好的方法可以继续?

我在server.js中创建了我的路线:

import express from 'express';
import compression from 'compression';
import bodyParser from 'body-parser';
import path from 'path';
import serialize from 'serialize-javascript';
import {navigateAction} from 'fluxible-router';
import debugLib from 'debug';
import React from 'react';
import ReactDOM from 'react-dom/server';
import app from './app';
import HtmlComponent from './components/Html';
import { createElementWithContext } from 'fluxible-addons-react';

const env = process.env.NODE_ENV;

const debug = debugLib('fluxible-posts');

const server = express();

server.use('/public', express.static(path.join(__dirname, '/build')));
server.use(compression());
server.use(bodyParser.urlencoded({ extended: true }));
server.use(bodyParser.json());

server.use((req, res, next) => {
    const context = app.createContext();

    debug('Executing navigate action');
    context.getActionContext().executeAction(navigateAction, {
        url: req.url
    }, (err) => {
        if (err) {
            if (err.statusCode && err.statusCode === 404) {
                // Pass through to next middleware
                next();
            } else {
                next(err);
            }
            return;
        }

        debug('Exposing context state');
        const exposed = 'window.App=' + serialize(app.dehydrate(context)) + ';';

        debug('Rendering Application component into html');
        const markup = ReactDOM.renderToString(createElementWithContext(context));
        const htmlElement = React.createElement(HtmlComponent, {
            clientFile: env === 'production' ? 'main.min.js' : 'main.js',
            context: context.getComponentContext(),
            state: exposed,
            markup: markup
        });
        const html = ReactDOM.renderToStaticMarkup(htmlElement);

        debug('Sending markup');
        res.type('html');
        res.write('<!DOCTYPE html>' + html);
        res.end();
    });
});

const port = process.env.PORT || 3000;
server.listen(port);
console.log('Application listening on port ' + port);

var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/fluxible-posts');

var Post = require('./database/postModel');


// routes
var router = express.Router();
server.use('/api/v1/', router); 

router.use(function(req, res, next) {
    // do logging
    console.log('Something is happening.');
    next(); // make sure we go to the next routes and don't stop here
});

// test route 
router.get('/', function(req, res) {
    res.json({ message: 'hooray! welcome to our api!' });   
});

router.route('/posts')
    .post(function(req,res) {
        var post = new Post();
        post.title = req.body.title;
        post.message = req.body.message;
        post.image = req.body.image;

        post.save(function(err) {
            if(err) {
                res.send(err);
            }
            res.json({ message : 'New post created' });
        });
    })
    .get(function(req, res) {
        Post.find(function(err, posts) {
            if (err)
                res.send(err);

            res.json(posts);
        });
    });

router.route('/posts/:post_id')

    // get the post with that id
    .get(function(req, res) {
        Post.findById(req.params.post_id, function(err, post) {
            if (err)
                res.send(err);
            res.json(post);
        });
    })

    // update the post with this id
    .put(function(req, res) {
        Post.findById(req.params.post_id, function(err, post) {

            if (err)
                res.send(err);

            post.name = req.body.name;
            post.save(function(err) {
                if (err)
                    res.send(err);

                res.json({ message: 'Post updated!' });
            });

        });
    })

    // delete the post with this id
    .delete(function(req, res) {
        Post.remove({
            _id: req.params.post_id
        }, function(err, post) {
            if (err)
                res.send(err);

            res.json({ message: 'Successfully deleted' });
        });
    });

export default server;

现在如果我想在我的项目中从另一个js文件发出POST请求,我该怎么办?

1 个答案:

答案 0 :(得分:0)

您的API看起来像是一个REST API。在这种情况下,您可以使用rest module