繁体   English   中英

Angular $ http POST无法将数据发送到express.js

[英]Angular $http POST unable to send data to expressjs

我试图将数据从角度数据发布到表达数据,但是,每次发出发布请求时,都会出现此错误。

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")
      });

默认情况下,expressjs在9000端口列出。 因此,您发布的网址应为http:// localhost:9000 / post /

您必须在服务器上启用CORS。 由于端口在同一服务器上不同,因此它将像跨域请求一样对待。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM