簡體   English   中英

如何在節點js + express中發出發布請求

[英]how to make post request in node js + express

我正在嘗試使用express + node.js發出發布請求。我安裝了這些插件package.json

{
  "name": "expressjs",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "body-parser": "^1.14.1",
    "express": "^4.13.3",
    "mongodb": "^2.0.47"
  }
}

我這樣發出要求

var express = require('express');
var mongodb = require('mongodb');

var app = express();


var bodyParser = require('body-parser');
app.use(bodyParser.json()); // support json encoded bodies
app.use(bodyParser.urlencoded({ extended: true })); // support encoded bodies

var MongoClient = require('mongodb').MongoClient;
var db;

// Initialize connection once
MongoClient.connect("mongodb://localhost:27017/abc", function(err, database) {
    if(err) throw err;

    db = database;

    // Start the application after the database connection is ready
    app.listen(3000);
    console.log("Listening on port 3000");
});

app.post('/api/users', function(req, res) {
    console.log('---')
    var user_id = req.body.id;
    var token = req.body.token;
    var geo = req.body.geo;

    res.send(user_id + ' ' + token + ' ' + geo);
});

當我點擊瀏覽器http:// localhost:3000 / api / users時 ,什么都沒有發生..

這是屏幕截圖 在此處輸入圖片說明

我也嘗試chrome rest client發送發帖請求..我在屏幕截圖中確實如此。但是我沒有收到服務器發出的任何控制台消息或響應,我做錯了..

我僅從控制台獲取此消息正在偵聽端口3000

在此處輸入圖片說明

第一張圖片顯示了GET請求,因為瀏覽器默認為GET 由於您不允許進行GET ,因此只是一個一般性錯誤。

使用ReST客戶端,您需要將標頭設置為Content-Type: application/json 然后這應該工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM