angular2 http.post() to local json file

后端 未结 2 663
情深已故
情深已故 2021-01-20 04:55

little help?

I am trying to write pure JSON to a file inside my project, my project tree looks like this:

src
->         


        
2条回答
  •  日久生厌
    2021-01-20 05:25

    Unfortunately, you can not PUT or POST directly to a file on your local filesystem using client side (browser) JavaScript.

    Consider building a simple server to handle a POST request. If you are most comfortable with JavaScript, try Express with Node.js

    // server.js
    'use strict'
    
    const bodyParser = require('body-parser');
    const express = require('express');
    const fs = require('fs');
    
    const app = express()
    app.use(bodyParser.json());
    
    app.use(function(req, res, next) {
      res.header('Access-Control-Allow-Origin', 'http://localhost:8000');
      res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
      res.header('Access-Control-Allow-Methods', 'POST');
      next();
    });
    
    app.post('/', (req, res) => {
      console.log('Received request');
      fs.writeFile('json.json', JSON.stringify(req.body), (err) => {
        if (err) throw err;
        console.log('File written to JSON.json');
        res.send('File written to JSON.json')
      })
    });
    
    app.listen(3000, ()=>{
      console.log('Listening on port 3000. Post a file to http://localhost:3000 to save to /JSON.json');
    });
    

提交回复
热议问题