2018.12.16 22:46 ES6学习中
Thejsway/chapter25
被自己蠢哭了TT
const multer = require('multer');
const express = require('express');
const bodyParser = require('body-parser');
const jsonParser = bodyParser.json();
const upload = multer();
const app = express();
const articles = [
{
id: 1,
title: 'First article',
content: 'Hello World!'
},
{
id: 2,
title: 'Lorem ipsum',
content:
'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut hendrerit mauris ac porttitor accumsan. Nunc vitae pulvinar odio, auctor interdum dolor. Aenean sodales dui quis metus iaculis, hendrerit vulputate lorem vestibulum.'
},
{
id: 3,
title: 'Lorem ipsum in French',
content:
'J’en dis autant de ceux qui, par mollesse d’esprit, c’est-à-dire par la crainte de la peine et de la douleur, manquent aux devoirs de la vie. Et il est très facile de rendre raison de ce que j’avance.'
}
];
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
next();
});
app.post('/api/cars', jsonParser, (request, response) => {
const cars = request.body;
response.send(`You sent me a list of cars: ${JSON.stringify(cars)}`);
});
app.post('/animals', upload.array(), (request, response) => {
const name = request.body.name;
const vote = request.body.strongest;
response.send(`Hello ${name}, you voted: ${vote}`);
});
app.post('/tshirt');
app.get('/hello', (request, response) => {
response.sendFile(`${__dirname}/views/hello.html`);
});
app.get('/api/articles', (request, response) => {
response.json(articles);
});
app.use(express.static('public'));
const listener = app.listen(process.env.PORT || 3000, () => {
console.log(`Your app is listening on port ${listener.address().port}`);
});
一直无法达成 自己发送请求给自建的服务器 的代码效果。然而,控制台一直在提示缺少东西…… 只要调换顺序就可以了…… 呵=。=
还不清楚 use
的意义是啥…… 被自己蠢到没心情记录了…… 就这样把……
又写了 tshirt
部分,然而,还是一头雾水了好久。
const travel = {
name: 'Sam',
countries: [
{ name: 'a', year: 1 },
{ name: 'b', year: 2 },
{ name: 'c', year: 3 }
]
};
// Send data to the server
fetch('http://localhost:3000/api/countries', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(travel)
})
.then(response => response.text())
.then(result => {
console.log(result);
})
.catch(err => {
console.error(err.message);
});
app.post('/api/countries', jsonParser, (request, response) => {
const travel = request.body;
console.log(travel);
// const travel = JSON.stringify(request.body);
// const name = JSON.stringify(request.body).name;
// let a = JSON.stringify(request.body);
// let travel = JSON.parse(a);
// console.log(travel);
// const name = travel.name;
// console.log(name);
// const length = travel.countries.length;
response.send(
`Your name is ${travel.name} and you visited ${travel.countries.length} countries. Keep traveling!`
);
});
一开始直接定义 name
与 countries
但是会未定义。不知道为啥,在 JSON
的类型上纠结了很久。原先的写法( key
不加双引号 并且 travel
被我写成了 Array
)似乎是有问题的。疯狂的修改之后最终谜之通过…… =。=改日再说