【发布时间】:2018-11-29 13:30:29
【问题描述】:
客户端浏览器:
API
class API {
constructor() {
this.api = "http://localhost:3000";
}
async authenticate(product_id) {
const url = this.api + '/api/auth';
const body = {
"product_id": product_id,
}
console.log(body);
const request = {
method: 'POST',
body: body,
}
return await fetch(url, request);
}
}
module.exports = API;
索引
const account = await this.API.authenticate("56729b6b77c82288f746c0cf");
console.log(account)
在我的控制台中我得到了
响应{类型:“cors”,网址:“http://localhost:3000/api/auth”, 重定向:false,状态:401,ok:false,...} body : (...) bodyUsed : 错误标头:标头{} ok:错误重定向:错误状态:401 statusText:“未经授权”类型:“cors”网址: "http://localhost:3000/api/auth"
Fetch 加载失败:POST "http://localhost:3000/api/auth"。
服务器端:
app.ts
import express from 'express';
import logger from 'morgan';
import bodyParser from 'body-parser';
import mongoose from 'mongoose';
import passport from 'passport';
import cors from "cors";
import Routes from './routes';
import Config from './config/config';
class App {
public app: express.Application;
public config: any;
constructor() {
this.app = express();
this.environment();
this.database();
this.middleware();
this.routes();
}
private environment(): void {
this.config = new Config();
}
private database(): void {
const uri: string = this.config.db.uri;
const options: any = this.config.db.options;
mongoose.connect(uri, options).then(
() => {
console.log("MongoDB Successfully Connected On: " + this.config.db.uri)
},
(err: any) => {
console.error("MongoDB Error:", err);
console.log('%s MongoDB connection error. Please make sure MongoDB is running.');
process.exit();
}
);
}
private middleware(): void {
this.app.use(cors());
this.app.use(logger('dev'));
this.app.use(express.json());
this.app.use(express.urlencoded());
this.app.use(passport.initialize());
}
private routes(): void {
const routes = new Routes(this.app);
}
}
export default App;
api/auth 路由
public store(req, res) {
console.log(req.body)
}
req.body 为空。
【问题讨论】:
-
@Randy 否,因为该请求在邮递员中工作正常
-
@Randy 我更新了我的问题,向您展示了我的服务器端应用程序的代码。你可以看到我已经设置了 cors 和 bodyParser。
-
我什至已经更新为使用 express.json 和 urlencoder 而不是 bodyparser,但这仍然不能解决问题。