我没有让内容类型更改为JSON,我已经尝试了很多方法,获取获取进入了函数,但发布却没有。
谢谢
我的代码:
index.js
const express = require('express');
let cors = require('cors');
let app = express();
const path = require('path');
const PORT = process.env.PORT || 5000;
app
.use(express.static(path.join(__dirname, 'public')))
.set('views', path.join(__dirname, 'views'))
.set('view engine', 'ejs');
app.use(cors(), function(req, res) {
res.type('json');
console.log("test b");
//req.header['Content-Type'] = 'application/json';
//req.header['Abadabadoo'] = 'hue';
});
app.options('*', cors(),function(req, res, next) {
res.type('json');
console.log("b");
//req.header['Content-Type'] = 'application/json';
//req.header['Abadabadoo'] = 'hue';
next();
});
app.post(cors(),function(req, res) {
console.log("c");
res.type('json');
//req.header['Content-Type'] = 'application/json';
//req.header['Abadabadoo'] = 'hue';
});
app.use(cors());
app.use(express.json())
app.listen(PORT, () => console.log(`Listening on ${ PORT }`));
获取
fetch(URL, {
method: 'POST',
mode:'cors',
body: JSON.stringify(toSend)
}).then(function (response) {
return response.json();
}).then(data => {
console.log(data);
}).catch(err => {
console.error('Failed retrieving information', err);
});
响应
{
email: Array [ "The email field is required." ]
password: Array [ "The password field is required." ]
}
请求标头
Accept */*
Accept-Encoding gzip, deflate, br
Accept-Language en-US,en;q=0.5
Connection keep-alive
Content-Length 40
Content-Type text/plain;charset=UTF-8
错误422无法处理的实体