【问题标题】:Angular $http POST unable to send data to expressjsAngular $http POST 无法将数据发送到 expressjs
【发布时间】:2016-03-19 11:03:45
【问题描述】:

我正在尝试从角度发布数据以表达,但是,每次我发出发布请求时都会收到此错误。

OPTIONS http://localhost/post/ net::ERR_CONNECTION_REFUSED(anonymous function) @ angular.js:11209s @ angular.js:11002g @ angular.js:10712(anonymous function) @ angular.js:15287m.$eval @ angular.js:16554m.$digest @ angular.js:16372m.$apply @ angular.js:16662(anonymous function) @ angular.js:24283m.event.dispatch @ jquery.js:4670r.handle @ jquery.js:4338
controller.js:29 

errorCallback 响应对象是:

Object {data: null, status: -1, config: Object, statusText: ""} 

我对 SO 上的其他类似问题进行了一些调整,例如添加标题、内容类型等。但没有运气。

这里似乎有什么问题。 谢谢

Controller.js

word.add = function(){
console.log(word.name );

    $http({
        method:'POST',
        url:'http://localhost/post/',
        data :word.name,
        headers: {'Content-Type': 'application/json'} 
    }).then(function successCallback(response){
        console.log(response);
        console.log("Successful");
    },function errorCallback(response){

        console.log(response);
        console.log("Unsuccessful");
    });     
};

app.js的相关代码摘录

 var routes = require('./routes/index');
    app.all('/*', function (request, response, next) {
       response.header("Access-Control-Allow-Origin", "*");
       response.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
        response.header("Access-Control-Allow-Headers", "X-Requested-With, Content-Type");
  next();
});

app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use('/post', routes);

index.js

var express = require('express');
var router = express.Router();
router.post('/post', function(request, response){
    console.log(request.body.name);
    response.send('Reached post');
});

module.exports = router;

编辑: 您好,我已经尝试在回复中添加内容类型标头。 不过,还是一样的错误。

当我使用这种方法发布时,相同的代码可以正常工作。

$http.post('/post',{data: word.name}).success(function(response) {
       console.log("success");
      }).error(function(err){
         console.log("failure")
      });

【问题讨论】:

  • 预检被触发。这意味着CORS 已就位。您可以使您的客户端和服务器位于同一个域中,也可以添加 CORS 标头。
  • @Phil 我已经研究了这个问题,并添加了 CORS,但仍然面临同样的错误。我不确定它是否与内容类型标题错误有关。
  • 好吧,net::ERR_CONNECTION_REFUSED 让我觉得你的 Express 服务器实际上没有运行(或者至少没有在端口 80 上运行)
  • 嗨,我遇到的一个奇怪的行为是,我能够在使用这种方法时成功发布数据。 $http.post('/post',{data: word.name}).success(function(response) { console.log("success"); }).error(function(err){ console.log("失败") });

标签: javascript angularjs node.js express


【解决方案1】:

您必须在服务器上启用 CORS。由于同一服务器上的端口不同,因此会将其视为跨域请求。

http://enable-cors.org/server_expressjs.html

【讨论】:

    【解决方案2】:

    expressjs 默认在 9000 端口列出。所以,你发帖的网址应该是http://localhost:9000/post/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-09
      • 2019-04-12
      • 2020-05-09
      • 2019-09-15
      • 1970-01-01
      相关资源
      最近更新 更多