angular2 http.post()到本地json文件 [英] angular2 http.post() to local json file

查看:143
本文介绍了angular2 http.post()到本地json文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

需要帮助吗?

我正尝试将纯JSON 写入文件内部我的项目中,我的项目树如下所示:

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

src
->app
-->components
--->people.component.ts
--->(other irrelevant components)
-->services
--->people.service.ts
-->data
--->JSON.json
->(other irrelevant src files)

people.component.ts中的代码仅用于调用和预订我的people.service.ts内部的函数,并传递newPerson属性,该属性是使用angular2 magic从DOM进行数据绑定的;这是name.service.ts中的功能:

The code in my people.component.ts is just used to call and subscribe to a function inside my people.service.ts, passing the newPerson property which is data-binded from the DOM using angular2 magic; this is the function inside name.service.ts:

public addPerson(newPerson) {
        let headers = new Headers();
        headers.append('Content-Type', 'application/json');
        return this.http.post('app/data/PEOPLE.json', newPerson, { header: headers })
        .map(res => res.json())
}

我的目标是在PEOPLE.json内编写(如有必要,请替换)newPerson属性(或整个文件).当然,当前的addPerson()函数将返回错误.

My objective is to write (if necessary replace) the newPerson property (or the entire file) inside PEOPLE.json. of course, the current addPerson() function returns an error.

我也尝试过put方法,它的错误略有不同,但是我没有找到任何一种方法的解决方案.

I've also tried the put method, it errors slightly differently, but i haven't found solutions to either method.

我绝对知道我要放入PEOPLE.json文件的数据的格式/类型不是错误.

I know categorically it's not an error with the format/type of data i'm trying to put in PEOPLE.json file.

推荐答案

不幸的是,您不能使用客户端(浏览器)JavaScript直接将PUT或POST到本地文件系统上的文件.

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

考虑构建一个简单的服务器来处理POST请求.如果您最喜欢JavaScript,请尝试使用Express.Node.js

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');
});

这篇关于angular2 http.post()到本地json文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆