接口测试问题,node写的后端接口,启动项目,浏览器能看到返回的字符串,postman测试返回一个错误的html代码?

练习前后端数据请求的时候,先用前端请求了网上免费接口,没问题数据拿到了。

测试本地后端接口,localhost:3000/users (这个是express项目生成时自带的router)

1、user.js

var express = require('express');
var router = express.Router();

/* GET users listing. */
router.get('/', function(req, res, next) {
  res.send('12344');
});

module.exports = router;

2、app.js(截取的,就是express项目生成时的代码)

var usersRouter = require('./routes/users');
app.use('/users', usersRouter);

3、用npm start启动项目,浏览器访问localhost:3000/users可以显示send的字符串
image.png

4、用postman测试localhost:3000/user接口,会返回一个显示错误信息的html结构
image.png
image.png

问:为什么两个测试方法结果不一样?

前端代码(只修改main.js和HelloWorld.vue)

index.js里添加

proxyTable: {
      '/api': {
        target:'http://localhost:3000/',
        changeOrigin:true, 
        pathRewrite:{  
          '^/api': '' 
        }
      }
    },

main.js

import Vue from 'vue'
import App from './App'
import axios from 'axios'

Vue.prototype.axios = axios
Vue.config.productionTip = false

new Vue({
 el: '#app',
 components: { App },
 template: '<App/>'
})

app.vue(原封不动)
HelloWorld.vue


<template>
  <div class="hello">
    <h1>{{ msg }}</h1>
  </div>
</template>

<script>
export default {
  name: 'HelloWorld',
  data () {
    return {
      msg: 'Welcome to Your Vue.js App'
    }
  },
  mounted(){
  //请求的接口
    this.axios.get("/api/users").then((res)=>{
      console.log(res);
    })
    
  }
}
</script>
<style scoped>
h1, h2 {
  font-weight: normal;
}
ul {
  list-style-type: none;
  padding: 0;
}
li {
  display: inline-block;
  margin: 0 10px;
}
a {
  color: #42b983;
}
</style>

访问localhost:8080,能拿到send的字符串了
image.png
控制台显示
image.png
但是再它返回的信息中有个
image.png
responseURL是响应的地址吧?不应该是localhost:3000响应的么?
api不是自动替换成localhost:3000么?

阅读 5.9k
3 个回答
  1. postman 的请求头里可能有 content-type: application/json 之类,导致服务器按照 json 格式解析请求,报错了
  2. 你请求的地址就是 :8080/api/users,只不过代理帮你 转接 了过去,并不是 替换,所以 requestURL 也没错。

你postman里输入的url有问题吧

image.png

我用你的代码复现不出来 说明你给出的代码是没问题的
问题出在其他地方

最好把完整的代码放上来,前端和node的,目前看不出什么问题来。
不过400是客户端错误的提示,应该和node代码没什么关系。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题