解决:启用CORS AngularJS发送HTTP POST请求 [英] SOLVED: Enable CORS AngularJS to send HTTP POST request

查看:1320
本文介绍了解决:启用CORS AngularJS发送HTTP POST请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过表单提交到我的服务器,这在不同的域(并启用CORS使用Node.js的服务器脚本)发送HTTP POST请求。

I want to send HTTP POST request by submitting form to my server, which in a different domain (and enabled cors in the server script using node.js).

这是所有角度配置脚本:

This is the script where all the Angular configurations are :

var myApp = angular.module('myApp', ['ngRoute']);

myApp.config(function($routeProvider, $locationProvider, $httpProvider) {

  $httpProvider.defaults.useXDomain = true;
  delete $httpProvider.defaults.headers.common['X-Requested-With'];

  $routeProvider
  .when('/', {
    controller: 'RouteCtrl',
    templateUrl: 'views/home_views.html'
  })
  .when('/login', {
    controller: 'RouteCtrl',
    templateUrl: 'views/login_views.html'
  })
  .when('/register', {
    controller: 'RouteCtrl',
    templateUrl: 'views/register_views.html'
  })
});

myApp.controller("UserController", function($scope, $http) {
  $scope.formData = {};
  $scope.clickMe = function() {
    console.log("Yay");
      $http({
        method: 'POST',
        url: 'http://localhost:8183/user/register',
        data: $.param($scope.formData),
      })
      .success(function(data) {
        console.log(data);
        if(!data.success) {
          console.log("error here");
        } else {
          console.log("error there");
        }
      });
  }
}); ...

我使用AngularJS 1.2.22,当它在本教程中陈述(的启用CORS )使CORS,它需要在配置手动启用CORS。但它仍然没有工作。以下是我从浏览器控制台了。

I'm using AngularJS 1.2.22 and as it stated in this tutorial (Enable CORS) to enable CORS, it needs to enable CORS manually in the config. But it's still not working. Here is what I got from the browser console.

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8183/user/register. This can be fixed by moving the resource to the same domain or enabling CORS.

我是很新的AngularJS所以任何帮助真的会pciated指出我犯任何错误AP $ P $ ..谢谢!

I'm quite new to AngularJS so any help would really be appreciated to point out any mistakes I made.. Thank you!

----编辑:添加server.js脚本----

var express = require('express'),
    app = express(),
    bodyParser = require('body-parser'),
    expressValidator = require('express-validator'),
    mysql = require('mysql'),
    crypto = require('crypto'),
    cors = require('cors'),
    uuid = require('node-uuid');

var connectionpool = mysql.createPool({
    connectionLimit: 1000,
    host: 'localhost',
    user: 'root',
    password: '',
    database: 'cloudvm'
});

app.listen(8183);
app.use(bodyParser.urlencoded({
    extended: true
}));

app.use(bodyParser.json());
app.use(expressValidator());
app.use(cors());


var user_router = express.Router();
var user_list = user_router.route('/list');
var user_register = user_router.route('/register');
var user_login = user_router.route('/login');

app.use('/user', user_router);

user_register.post(function(req, res, next) {

    var errors = req.validationErrors();
    if (errors) {
        res.status(200);
        res.send(errors);
        console.log(errors);
        return;
    }
    var data = {
        name_user: req.body.name,
        email_user: req.body.email,
        password_user: req.body.password,
        no_telp_user: req.body.no_telp,
        company_name_user: req.body.company_name,
        address_user: req.body.address,
        name_cc_user: req.body.name_cc,
        address_cc_user: req.body.address_cc,
        no_cc_user: req.body.no_cc,
        no_vcv_user: req.body.no_vcv,
        expire_month_cc_user: req.body.expire_month,
        expire_year_cc_user: req.body.expire_year
    };

    connectionpool.getConnection(function(err, connection) {
        if (err) {
            console.error('CONNECTION ERROR:', err);
            res.statusCode = 503;
            res.send({
                result: 'error',
                err: err.code
            });
        } else {
            var sql = 'INSERT INTO user SET ?';
            console.log(sql)
            connection.query(sql, data, function(err, rows, fields) {
                if (err) {
                    console.error(err);
                    res.statuscode = 500;
                    res.send({
                        result: 'error',
                        err: err.code
                    });
                }
                res.send([{
                    msg: "registration succeed"
                }]);
                connection.release();
            });

        }

    });
});

-------解决了!下面是解-------

感谢您对种答案,但我已经成功地在我的服务器脚本(在节点上运行)启用CORS然后我试图用这个

Thank you for the kind answers, but I've managed to enable CORS on my server script (running on Node) then I tried to use this

headers: { 'Content-Type': 'application/x-www-form-urlencoded' }

这是当HTTP请求被称为我的客户端脚本,那么它终于让我得到来自服务器的响应而无需CORS问题!所以,我想这可能是头部的问题。所以,谢谢你那种反应!希望这将有助于在未来有这个问题的人!

on my client-side script when the http request is called, then it finally let me to get response from the server without having the CORS problem! So, I thought it might be the header problem .. So, thank you for kind responses! Hope this would help anyone having this problem in the future!

推荐答案

这就是我做的前preSS应用CORS,你要记住,因为一些框架有2呼吁CORS选项,第一个是OPTIONS哪些检查什么方法都可以,然后有实际呼叫,OPTIONS需要的只是空的答案 200 OK

That's how I do CORS in express applications, you have to remember about OPTIONS because for some frameworks there are 2 calls for CORS, first one is OPTIONS which checks what methods are available and then there is actual call, OPTIONS require just empty answer 200 OK

allowCrossDomain = function(req, res, next) {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
  res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With');
  if ('OPTIONS' === req.method) {
    res.send(200);
  } else {
    next();
  }
};

app.use(allowCrossDomain);

这篇关于解决:启用CORS AngularJS发送HTTP POST请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆