Angular前端无法从Express后端获得对HTTP请求的适当响应

时间:2019-05-07 19:39:29

标签: node.js angular express

我正在使用Angular 7向Express 4后端代码发送http请求,但始终得到404响应作为回报。我认为这可能与我列出http请求路径的方式有关,但不确定。这是我第一次尝试这样的事情。我已经在Angular中设置了proxy.conf.js文件,以允许跨源通信(Angular在localhost:4200上运行,在localhost:8085上运行)。我的Express代码保存在C:/ ABC / myapp下。以下是相关代码:

Angular proxy.conf.js文件:

public void btnSend_onClick(View v) {
    EditText mEdit = findViewById(R.id.tbxNumber);
    writeCustomCharacteristic(Integer.parseInt(mEdit.getText().toString()));

}

private BluetoothManager mBluetoothManager;
private BluetoothAdapter mBluetoothAdapter;
private BluetoothGatt mBluetoothGatt;
private static final String TAG = "MyActivity";

/**
 * Initializes a reference to the local Bluetooth adapter.
 *
 * @return Return true if the initialization is successful.
 */
public boolean initialize() {
    // For API level 18 and above, get a reference to BluetoothAdapter through
    // BluetoothManager.
    if (mBluetoothManager == null) {
        mBluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
        if (mBluetoothManager == null) {
            Log.e(TAG, "Unable to initialize BluetoothManager.");
            return false;
        }
    }

    mBluetoothAdapter = mBluetoothManager.getAdapter();
    if (mBluetoothAdapter == null) {
        Log.e(TAG, "Unable to obtain a BluetoothAdapter.");
        return false;
    }

    return true;
}

public void writeCustomCharacteristic(int value) {
    EditText mEdit = findViewById(R.id.tbxNumber);
    if (mBluetoothAdapter == null || mBluetoothGatt == null) {
        Toast.makeText(MainActivity.this, "BluetoothAdapter not initialized",Toast.LENGTH_SHORT).show();
        return;
    }
    /*check if the service is available on the device*/
    BluetoothGattService mCustomService = mBluetoothGatt.getService(UUID.fromString("252b926b-100f-4e10-8d33-ff1ffccb89fe"));
    if(mCustomService == null){
        Toast.makeText(MainActivity.this, "Custom BLE Service not found",Toast.LENGTH_SHORT).show();
        return;
    }
    /*get the read characteristic from the service*/
    BluetoothGattCharacteristic mWriteCharacteristic = mCustomService.getCharacteristic(UUID.fromString("61f1c75b-1246-46f0-acf9-3aa6c078e5c5"));
    mWriteCharacteristic.setValue(value,android.bluetooth.BluetoothGattCharacteristic.FORMAT_UINT8,0);
    if(mBluetoothGatt.writeCharacteristic(mWriteCharacteristic) == false){
        Toast.makeText(MainActivity.this, "Failed to write characteristic",Toast.LENGTH_SHORT).show();
    }
    Toast.makeText(MainActivity.this, "Die Nummer: '" + mEdit.getText().toString() + "' wurde an das Display übertragen",Toast.LENGTH_LONG).show();
}

发送http请求的角度服务代码:

{
  "/": {
    "target": "http://localhost:8085",
    "secure": false,
    "logLevel": "debug"
  }
}

快速app.js代码:

export class ContactUsService {
private url = '/contactus';
private result: any;
message: string;

addMessage(contactUsMessage: contactUsInterface): Observable<contactUsInterface> {
  return this.http.post<contactUsInterface>(this.url, contactUsMessage). (retry(3));
};

constructor(private http: HttpClient) {}
};

contactUs.js代码(用于contactUsRouter):

var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var createError = require('http-errors');
var express = require('express');
var logger = require('morgan');
var mongoose = require('mongoose');
var path = require('path');
var winston = require('winston');
var contactUsRouter = require(path.join(__dirname, 'routes', 'contactUs'));
var app = express();

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/contactus', contactUsRouter);

app.use(function(req, res, next) {
  next(createError(404));
});
app.use(function(err, req, res, next) {
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;

当我进入contactus页面(URL:localhost:4200 / contactus)并执行表单的提交按钮时,出现以下错误: 在浏览器控制台中:“ HTTP404:未找到-服务器未找到与请求的URI(统一资源标识符)匹配的任何内容。 (XHR)POST-http://localhost:4200/contactus

在npm日志中:“ POST / contactus 404 3.081 ms-2128 错误:无法在视图目录“ C:\ ABC \ myapp \ views”中查找视图“错误”。

关于我做错了什么的智慧之语?

2 个答案:

答案 0 :(得分:1)

当前,由于要使用语句POST /contactus/contactus指定基本路由,因此要公开app.use('/contactus', contactUsRouter);的路由,然后在POST的注册中添加/附加附加/附加/contactus / PUT路线。

尝试将POST路由更改为仅'/'的路径:

var express = require('express');
var router = express.Router();
var contactUsMessage = require('../models/contactUsMessage');

  router.route('/')
    .get(function(req,res,next){
      res.send("Hello")
    })
    .post(function(req,res,next){
      res.send("Hello")
    });

module.exports = router;

希望有帮助!

答案 1 :(得分:1)

您的代理配置文件无法正常工作。

请求仍在尝试在端口4200 (((XHR)POST-http://localhost:4200/contactus上运行的角度应用程序中查找POST方法路由 / contactus 它不存在,因此您得到的是404。

确保您已按照官方角度网站Add Proxy for backend server - angular.io

所述的步骤进行操作

如果您使用代理路径 / api 而不是 / ,则是明智的选择。像这样

{
  "/api": {
    "target": "http://localhost:8085",
    "secure": false
  }
}

希望有帮助