我几个小时都在解决这个问题
我有一个简单的带有数据服务的客户端,该客户端从epxress js服务器获取数据,并允许通过发布请求创建数据。
GET请求仅适用于代理。该帖子根本无效。
我在服务器端收到请求,但是主体为空,似乎存在一些我不理解的cors问题
客户端'proxy.conf.json'
中的代理{
"/": {
"target": "http://127.0.0.1:3000",
"secure": false,
"logLevel": "debug"
}
}
运行ng serve --proxy-config=proxy.conf.json
import { Injectable } from '@angular/core';
import {HttpClient,} from '@angular/common/http';
import {Dog} from './Dog';
@Injectable({
providedIn: 'root'
})
export class DataService {
constructor(private httpclient:HttpClient) { }
async get_dogs(){
return await this.httpclient.get<Dog[]>('/dogs').toPromise();
}
async create_dog(dog){
return await this.httpclient.post<Dog>('/dogs',dog).toPromise();
}
}
表达.js
const express = require('express');
const bodyParser = require('body-parser');
const {initElements, createElement } = require('./utils');
const app = express();
const port = 3000;
const dogsRouter = express.Router();
app.use(bodyParser.text());
app.listen(port, () => console.log(`Example app listening on port ${port}!`));
app.get('/', (req, res) => res.send('Hello World!'));
const dogs = [];
initElements(dogs);
app.use('/dogs', dogsRouter);
// Get all dogs
dogsRouter.get('/', (req, res, next) => {
res.send(dogs);
});
// Create an expression
app.post('/dogs', (req, res, next) => {
console.log(req);
const newDog = createElement(req.query);
if (newDog) {
dogs.push(newDog);
res.status(201).send(newDog);
} else {
res.status(400).send();
}
});