【发布时间】:2022-02-20 09:25:21
【问题描述】:
我正在开发和应用程序进行搜索,当用户在输入框中键入时,发送一个帖子请求以检查数据库(猫鼬)以查看它是否存在,如果存在 响应将有效负载发送回具有匹配名称的客户端。当我在框中输入时,我得到 UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'payload' of undefined 从服务器。在 chrome 开发工具中,状态为待处理。根据我的研究, req.body.payload 其中 body 是属性。 我添加了 app.use(express.json() 并且我什至尝试过 const bodyParser = require('body-parser') app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())。 在我的路由上添加一个虚拟处理程序时,我确实从客户端收到了状态为 200 的请求。这是一个代码 sn-p。
My server.js
const press.Router();
const someProducts = require('./liveSearch');
const getProducts =
require('.../../controllers/api/getProducts/getProducts')
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/productLiveSearch',
{useNewUrlParser:
true, useUnifiedTopology: true, });
const db = mongoose.connection;
db.on('error', error => console.log(error));
db.once('open', () =>{
console.log('Connected to Mongoose');
const app = express();
app.use(express.json());
app.use(express.urlencoded({extended: true}));
app.use(function(req,res,next){
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
res.header('Access-Control-Allow-Methods','POST, GET ,DELETE, PUT');
next();
});
});
const app = express();
app.options('/getProducts', cors()) // enable pre-flight
app.use(cors({
origin: [
'http://localhost:4200' ]
}))
app.use('/', getProducts)
app.use('/getProducts', getProducts);
app.get('/', function(req, res){
res.send('hello world');
});
app.listen(process.env.Port|| 3000, () => {
console.log("Server has started on Port 3000");
});
module.exports = router
my getProducts.js
var express = require('express');
const cors = require('cors');
const someProducts = require('../liveSearch');
var router = express.Router();
const bodyParser = require('body-parser')
const app = express();
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())
router.get('/', function(req, res){
res.send('GET route on things here.');
});
router.post('/getProducts', async(req,res) =>{
console.log("Does it get to post");
payload: req.body.payload;
console.log("does it get pass")
let search = await someProducts.find({name: {$regex: new RegExp('^'+payload+'.*',
'i')}}).exec();
//Limit search to 10
search = search.slice(0, 10);
//res.send("got a post request")
res.send({payload:payload});
})
//export this router to use in our server.js
module.exports = router;
My post request is in my searchservice.ts
import { Injectable } from '@angular/core';
import{HttpClient, HttpHeaders} from '@angular/common/http';
import{map, catchError, tap} from 'rxjs/operators'
//import { Product } from '@app/models/product';
import { Observable } from 'rxjs';
import {MessengerService} from 'src/app/services/messenger.service';
import {productsUrl} from '@app/ui/header/api'
import { productUrl } from '@app/config/api';
export interface someProducts{
_id: string,
name: string
}
@Injectable({
providedIn: 'root'
})
export class SearchService {
constructor(private http:HttpClient, private messageService:MessengerService) { }
searchProducts(query:string){
console.log("Does it get my searchProducts");
return this.http.post<{payload: Array<someProducts>}>(productsUrl, {payload:query}, {
headers:new HttpHeaders({'Content-Type': 'application.json'})
}).pipe(
map(data =>data.payload)
);
}
}
Thanking You in Advance.
PH
【问题讨论】:
-
请将
POST请求分享给/getProducts -
我的帖子请求在我添加的 searchserve.ts 中
-
您好,我的帖子请求在我添加的 searchservice.ts 文件中
-
我建议分析/分享请求本身,而不是创建请求的逻辑。最有可能的是,您在某个地方遇到了一个小错误,即您没有正确设置有效负载属性。一般来说,可以通过提供minimal reproducible example 来改进问题的格式。