Cross Origin Post Request Angular js

时间:2018-05-17 21:35:48

标签: angularjs node.js express jsf cross-domain

我正在尝试使用Angular js发布帖子请求,但它不起作用。原始URL与服务器不同。服务器是Node Express应用程序,其基本URL是“localhost:3000”。 Client是在Tomcat服务器上运行的java Web应用程序,其基本URL是“localhost:8080”。

我的服务器有以下文件:

app.js:

var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');

var app = express();

// Add headers
app.use(function (req, res, next) {

    // Website you wish to allow to connect
    res.setHeader('Access-Control-Allow-Origin', 'http://localhost:8080');

    // Request methods you wish to allow
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');

    // Request headers you wish to allow
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');

    // Set to true if you need the website to include cookies in the requests sent
    // to the API (e.g. in case you use sessions)
    res.setHeader('Access-Control-Allow-Credentials', true);

    // Pass to next layer of middleware
    next();
});

var cons = require('consolidate');

// view engine setup
app.engine('html', cons.swig);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'html');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);
app.use('/users', usersRouter);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
    next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
    // set locals, only providing error in development
    res.locals.message = err.message;
    res.locals.error = req.app.get('env') === 'development' ? err : {};

    // render the error page
    res.status(err.status || 500);
    res.render('error');
});

module.exports = app;

index.js:

var express = require('express');
var router = express.Router();
var db = require('../queries');

router.get('/api/comments', db.getAllComments);
router.get('/api/comments/:id', db.getSingleComment);
router.post('/api/comments/create', db.createComment);
router.post('/api/comments/update', db.updateComment);
router.post('/api/comments/delete', db.removeComment);

router.get('/', function(req, res, next) {
    res.render('index', { title: 'Index' });
});

router.get('/update', function(req, res, next) {
    res.render('update', { title: 'Update' });
});

router.get('/delete', function(req, res, next) {
    res.render('delete', { title: 'Delete' });
});

module.exports = router;

queries.js:

var promise = require('bluebird');

var options = {
    promiseLib: promise
};

var pgp = require('pg-promise')(options);
var connectionString = 'postgresql://pgpadrao:pgpadrao123@localhost:5432/db_onepageenterprises';
var db = pgp(connectionString);

module.exports = {
    getAllComments: getAllComments,
    getSingleComment: getSingleComment,
    createComment: createComment,
    updateComment: updateComment,
    removeComment: removeComment
};

function getAllComments(req, res, next) {
    db.any('select * from tbl_comentario order by datahora desc')
    .then(function (data) {
        res.status(200)
        .json({
            status: 'success',
            data: data,
            message: 'Retrieved ALL comments'
        });
    })
    .catch(function (err) {
        return next(err);
    });
}

function getSingleComment(req, res, next) {
    var commentID = parseInt(req.params.id);
    db.one('select * from tbl_comentario where id = $1', commentID)
    .then(function (data) {
        res.status(200)
        .json({
            status: 'success',
            data: data,
            message: 'Retrieved ONE comment'
        });
    })
    .catch(function (err) {
        return next(err);
    });
}

function createComment(req, res, next) {
    db.none('insert into tbl_comentario(id, comentario, datahora, usuario)' + ' values(default, ${comentario}, current_timestamp, ${usuario})',
    req.body)
    .then(function () {
        res.status(200)
        .json({
            status: 'success',
            message: 'Inserted one comment'
        });
    })
    .catch(function (err) {
        return next(err);
    });
}

function updateComment(req, res, next) {
    db.none('update tbl_comentario set comentario=$1 where id=$2',
    [req.body.comentario, parseInt(req.body.id)])
    .then(function () {
        res.status(200)
        .json({
            status: 'success',
            message: 'Updated comment'
        });
    })
    .catch(function (err) {
        return next(err);
    });
}

function removeComment(req, res, next) {
    var commentID = parseInt(req.body.id);
    db.result('delete from tbl_comentario where id = $1', commentID)
    .then(function (result) {
        res.status(200)
        .json({
            status: 'success',
            message: `Removed ${result.rowCount} comment`
        });
    })
    .catch(function (err) {
        return next(err);
    });
}

按照我的页面发出请求。这是一个.xhtml页面

<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"             "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:ui="http://java.sun.com/jsf/facelets"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:f="http://java.sun.com/jsf/core"
    xmlns:p="http://primefaces.org/ui">
<h:head>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
    <link rel="shortcut icon" type="image/x-icon"
    href="#{request.contextPath}/resources/images/favicon.png" />
    <title>Comentário</title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
    <script src='https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular-resource.js'></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

    <script>
    angular.module('commentApp', []).controller('commentController', function($scope, $http) {
        $http.get('http://localhost:3000/api/comments')
            .then(function(response) {
                $scope.comments = response.data;
            });
    });
    </script>
</h:head>
<ui:decorate template="/template/templateusuario.xhtml">
    <ui:define name="page">
        <div ng-app="commentApp" ng-controller="commentController"
        align="center">

            <label id="comment" ng-repeat="x in comments.data">{{ x.comentario }}<br /><br /></label>
            <br />
        </div>

        <div ng-app="comentarApp" ng-controller="comentarController" align="center">
            Comentário: <input type="text" name="comentario" class="novoComentario" /><br />
            <input type="hidden" name="usuario" value="#{usuarioController.usuario.login}" />
            <button ng-click="SendData()" class="botaoComentar" >Comentar</button>
        </div>

    </ui:define>
</ui:decorate>
</html>

我刚刚尝试了所有内容,如何发布消费以下网址的帖子请求:

http://localhost:3000/api/comments/create

如何从此页面向上述网址发送帖子请求?

1 个答案:

答案 0 :(得分:0)

一种可行的方法是使用普通的HTML格式,因为JSF 不支持action属性,这意味着我们无法提交后期操作。

下面的代码解决了我的问题:

<form action="http://localhost:3000/api/comments/create" method="post">
    <label for="comentario">Comentário:</label>
    <input type="text" id="comentario" name="comentario" class="novo-comentario" ng-click="SendData()" class="botao-comentar"/><br />
    <input type="submit" value="Comentar">
</form>