客户端浏览器:
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;
INDEX
const account = await this.API.authenticate("56729b6b77c82288f746c0cf");
console.log(account)
在我的控制台中,我得到
响应{type:“ cors”,url:“ http://localhost:3000/api/auth”, 重定向:false,状态:401,确定:false,...}正文:(...)正文 错误的标头:标头{}好的:错误的重定向:错误的状态:401 statusText:“未经授权”类型:“ cors”网址: “ http://localhost:3000/api/auth”
加载失败: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)
}
需求主体为空。
答案 0 :(得分:2)
您应该尝试在请求模式下添加:cors在您的请求中。正文应该是一个字符串,您可能希望将内容类型的标头设置为application / json:
let headers = new Headers();
headers.set('Content-type', 'application/json');
const request = {
method: 'POST',
body: JSON.stringify(body),
mode: 'cors',
credentials: 'include',
headers: headers
}
在浏览器的“网络”标签中查看会发生什么也会很有帮助。