【问题标题】:Unable to Post in Angular / Express无法在 Angular / Express 中发布
【发布时间】:2015-09-20 07:41:10
【问题描述】:

我正在尝试使用 Angular 发布,但不断收到 404 错误。看起来请求没有被提出。任何想法为什么?感谢大家的帮助。

  var param = $scope.tag;
// client
  $http({method: 'Post', url: '/api', headers: {
  "Content-Type": "application/json", "Access-Control-Allow-Origin": "*" }, data: {tag: param}})
    .then(function(response) {
      console.log(response);
    });

// server
app.post('/api', function (req, res) {
  var tag = req.body.tag;
  request("http://food2fork.com/api/search?key=KEY&q=" + tag, function (req, res) {
    res.json(response);
  });
});

// request headers
Accept:application/json, text/plain, */*
Accept-Encoding:gzip, deflate
Accept-Language:en-US,en;q=0.8
Access-Control-Allow-Origin:*
Cache-Control:no-cache
Connection:keep-alive
Content-Length:17
Content-Type:application/json
Host:localhost:3000

// response headers
Connection:keep-alive
Content-Length:22
Content-Type:text/html; charset=utf-8
Date:Sat, 19 Sep 2015 23:22:15 GMT
X-Content-Type-Options:nosniff
X-Powered-By:Express

【问题讨论】:

    标签: javascript angularjs http express


    【解决方案1】:

    您不必使用所有这些代码。试试:

    // Client:
    var tag = $scope.tag;
    
    $http.post('/api', {tag: tag})
      .then(function(response) {
        console.log(response);
    });
    
    //Server:
    var bodyParser = require('body-parser');
    app.use(bodyParser.json());
    
    app.post('/api', function(req, res) {
      var tag = req.body.tag;
      res.send(tag);
    });
    

    【讨论】:

    • 我已经尝试了你的代码,但我收到了这个错误:POST localhost:3000/api net::ERR_CONNECTION_REFUSED 另外,我的请求标头显示:临时标头显示
    【解决方案2】:

    使用method: 'POST' 而不是method:'Post'

    后者无法识别,并发出默认 GET 而非您期望的 POST。

    编辑:检查了代码,我上面写的不是真的

    除此之外...不应该是一些类似的 URL

    /api/tags
    

    ???

    【讨论】:

    • 我将其更改为“POST”,但仍然收到 404 错误。这样做的目的是让我可以获取参数并在服务器上使用它。
    • 您可以从开发者工具中发布请求信息吗?
    • 您是否在寻找响应标头?我更新了帖子以显示两者。
    • 不,我正在寻找类似“POST:localhoat:3000...”的内容。请同时发布您使用的服务器端代码。类似“app.post (...)”的东西
    • POST localhost:3000/api net::ERR_CONNECTION_REFUSED b @ angular.js:10661 q @ angular.js:10480 d.$get.g @ angular.js:10187 (匿名函数) @ angular.js :14634 a.$get.n.$eval @ angular.js:15916 a.$get.n.$digest @ angular.js:15727 a.$get.n.$apply @ angular.js:16024 (匿名函数) @ angular.js:23416 c @ angular.js:3293 我还使用服务器端代码编辑帖子。
    猜你喜欢
    • 1970-01-01
    • 2014-08-20
    • 2023-03-28
    • 2020-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-23
    相关资源
    最近更新 更多