Показать сообщение отдельно
  #3 (permalink)  
Старый 26.07.2021, 16:06
Аспирант
Отправить личное сообщение для Konstantin47 Посмотреть профиль Найти все сообщения от Konstantin47
 
Регистрация: 12.01.2021
Сообщений: 32

можно вернуться к теме delete
переделал, сделал запросы GET, POST ( читало и записывало в Json)

код, который работает


var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var fs = require('fs');
​ const path = require('path');

​ 
​ app.use(bodyParser.urlencoded({ extended:true}));
​ app.use(express.static(__dirname+'/public'));
​

app.post('/process_post',​ (req, res) => {

​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ // należy utworzyć nowy obiekt
​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ const newWeather = {
​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ 
​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ id: 1, location: req.body.location,
​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ id: 2, temperature: req.body.temperature,
​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ id: 3, humidity: req.body.humidity,
​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ id:4, pressure: req.body.pressure
​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ };
​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ console.log(req.body)
​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ // pobrać aktualne dane z pogodą
​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ const weather = JSON.parse(fs.readFileSync("weather.json"));

​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ // dodać do nich nową pogodę
​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ weather.push(newWeather);

​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ // i napisać zapisać dane do pliku
​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ fs.writeFileSync("weather.json", JSON.stringify(weather));
​ ​ ​ ​ ​ ​ ​ ​ ​ res.json(newWeather);
});

app.get('/process_get',​ function (req, res) {
const records = JSON.parse(fs.readFileSync("weather.json"));
​ ​ ​ ​ const weather = JSON.parse(fs.readFileSync("weather.json"));
​ 
​ ​ ​ ​ res.json(weather);
​ ​ 
});

​

​
// не работает
​ app.delete('/delete/:id', function(req, res) {
​ ​ ​ 
​ ​ ​ const weather = JSON.parse(fs.readFileSync("weather.json"));
var id = req.param("id");
​ ​ ​ weather.remove({
​ ​ ​ ​ ​ ​ ​ _id: id
​ ​ ​ }, function(err){
​ ​ ​ ​ ​ ​ ​ if (err) {
​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ console.log(err)
​ ​ ​ ​ ​ ​ ​ }
​ ​ ​ ​ ​ ​ ​ else {
​ ​ ​ ​ ​ ​ ​ ​ ​ ​ return res.send("Removed");
​ ​ ​ ​ ​ ​ ​ }
​ ​ ​ });
​ ​ ​ 
​ ​ ​ fs.writeFileSync("weather.json", JSON.stringify(weather));
​ ​ ​ ​ ​ ​ ​ ​ ​ res.json(newWeather);
});

​ ​ 
// пример для себя фильтра 
let someUsers = users.filter(item => item.id < 3);

​ 
​ 
var server = app.listen(8081, function () {
​ ​ var host = server.address().address
​ ​ var port = server.address().port
​ ​ 
​ ​ console.log("Example app listening at //%s:%s", host, port)
​ 
})




<body>   
      
    <center>  <form action = "//127.0.0.1:8081/process_get" method = "GET"> 
	<br>
       Location: <input type = "text" name = "location">  <br>
		 <br>
		 <br>
            
		 
		temperature: temperaturę w st. C
<input type=" text" name="temperature">  C<br><br>

humidity: wilgotność powietrza w %
<input type="text" name="humidity" >  %<br><br>
pressure: ciśnienie w hPa
<input type="text" name="pressure" >  hPa<br><br>
<br>
 <input type = "submit" value = "GET">
      </form>
	  
	  
	   <center>  <form action = "//127.0.0.1:8081/process_post" method = "POST">
       Location: <input type = "text" name = "location">  <br>
		 <br>
		 <br>
            
		 
		temperature: temperaturę w st. C
<input type=" text" name="temperature">  C<br><br>

humidity: wilgotność powietrza w %
<input type="text" name="humidity" >  %<br><br>
pressure: ciśnienie w hPa
<input type="text" name="pressure" >  hPa<br><br>

<br>
 <input type = "submit" value = "POST">
      </form>
	  
	   <br>
	   
	   

	   <center>  <form action = "//127.0.0.1:8081/process_delete" method = "POST">	


	  <select>
  <option>  Location: <input type = "text" id="1" name = "location"></option>
  <option>temperature: <input type=" text" id="2" name="temperature"> </option>
  <option>humidity: <input type="text" id="3" name="humidity" > </option>
  <option>pressure: <input type="text" id="4" name="pressure" ></option>

</select>   


  <input type = "submit" value = "DELETE">
  </form>
       
   </body>


Html

вопрос, метод post или все таки delete

В форме же input не должно ж ничего появляться? что мол, файл json прочитан, input же пустой по идее будет

отдельно вынес id, чтобы удалять этот массив.

и еще вопрос, в самом удаление html button точно также управляется, как и в пост , гет?

да я ссоздал файл json cпустым массивом и данные с пост в него нормально записываются и показываются в браузере
Гет тоже нормально все показывает

ps проблема моя с удалением пост


Спасибо
Ответить с цитированием