首页 > 解决方案 > 试图让 Supertest 将正文发送到 https 帖子?

问题描述

我是新手,无法让超测试为我工作。我想知道:

	"use strict";
	
	const request = require('supertest');
	const express = require('express');
	const https = require('https');
	const fs = require('fs');
	const path = require('path');
	const certPath = path.resolve(path.resolve(), './certs');
	
	const app = express();
	
	//This line is from the Node.js HTTPS documentation.
	const options = {
		key : fs.readFileSync(certPath+'/server-key.pem'),
		cert : fs.readFileSync(certPath+'/server-crt.pem'),
		ca : fs.readFileSync(certPath+'/ca-crt.pem')
	};
	
	// service
	app.post('/failService', function(req, res) {
		console.log('failService: '+req.body); // failService: undefined
		res.send('hello');
	});
	
	describe('trial not working', function() {
	  it('responds with json', function(done) {
		  request(app)
	      .post('/failService')
	      .send({name: 'john'})
	      .set('Accept', /json/)
	      .expect(200)
	      .end(function(err, res) {
	        if (err) return done(err);
	        console.log('response: '+res.body); // response: [object Object]
	        done();
	      });
	  });
	});

.... 显示

$ mocha supertest.js

  trial not working
failService: undefined
response: [object Object]
    √ responds with json (125ms)


  1 passing (171ms)

请注意,证书(不包括在内)是自签名的。

标签: node.jsexpresshttpssupertest

解决方案


这是由于自签名证书。

我也遇到了类似的问题,有两种可能的解决方案

  1. 为测试环境创建http服务器而不是https服务器
  2. 替换supertestsuperrequestnpm 包并将 strictSsl 设置为 false。

推荐阅读