Сервер узла загружается только на локальном хосте Safari, а не в Chrome. - PullRequest
0 голосов
/ 24 июня 2019

Узловой сервер, использующий http://localhost:8000, работает только в Safari, но не в Chrome. Использование 127.0.0.1:8000 будет работать как на Safari, так и на Chrome. Я запутался, почему использование localhost не будет работать в моем браузере Chrome. Набрал в моем терминале ping localhost и получил 127.0.0.1

До обновления до angular 8 мой проект работал нормально и смог запустить его на моем локальном хосте. После обновления у меня возникли некоторые проблемы, поэтому я решил вернуться к версии angular 7. С тех пор я могу запускать свой проект только с использованием своего IP-адреса и локального хоста, но только с использованием Safari, а не Chrome. Есть идеи, в чем проблема или как это исправить?

server.js

const express = require('express');
const app = express();
const path = require('path');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const session = require('express-session');
const mongooseDatabase = require("./server/config/mongoose");
const userRoutes = require('./server/config/routes/users');
const taskRoutes = require('./server/config/routes/tasks');

//Body Parser Middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

app.use(express.static(__dirname + '/dist/todo'));

app.use(session({
    secret:"thisisasecret",
    saveUninitialized:true,
    resave:false,
    cookie: {maxAge:1000}
}))
app.set('trust proxy', 1);
mongoose.connect(mongooseDatabase.database, { useCreateIndex: true, useNewUrlParser:true });

mongoose.connection.on('connected', () => {
    console.log("Connected to database " + mongooseDatabase.database);
})
mongoose.connection.on('error', (err) => {
    console.log("Database database " + err);
})


app.use('/users', taskRoutes, userRoutes);
taskRoutes(app);
userRoutes(app);

app.all("*", (req,res,next) => {
    res.sendFile(path.resolve("./dist/todo/index.html"))
});


app.listen(8000, () => console.log("Running on port 8000"));

Глобальная версия

     _                      _                 ____ _     ___
    / \   _ __   __ _ _   _| | __ _ _ __     / ___| |   |_ _|
   / △ \ | '_ \ / _` | | | | |/ _` | '__|   | |   | |    | |
  / ___ \| | | | (_| | |_| | | (_| | |      | |___| |___ | |
 /_/   \_\_| |_|\__, |\__,_|_|\__,_|_|       \____|_____|___|
                |___/


Angular CLI: 7.3.4
Node: 10.16.0
OS: darwin x64
Angular:
...

Package                      Version
------------------------------------------------------
@angular-devkit/architect    0.13.4
@angular-devkit/core         7.3.4
@angular-devkit/schematics   7.3.4
@schematics/angular          7.3.4
@schematics/update           0.13.4
rxjs                         6.3.3
typescript                   3.2.4

package.json

{
  "name": "todo",
  "version": "0.0.0",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "~7.2.0",
    "@angular/common": "~7.2.0",
    "@angular/compiler": "~7.2.0",
    "@angular/core": "~7.2.0",
    "@angular/forms": "~7.2.0",
    "@angular/material": "^6.2.1",
    "@angular/platform-browser": "~7.2.0",
    "@angular/platform-browser-dynamic": "~7.2.0",
    "@angular/router": "~7.2.0",
    "angular2-flash-messages": "^3.0.1",
    "body-parser": "^1.19.0",
    "core-js": "^2.5.4",
    "express": "^4.17.1",
    "express-session": "^1.16.2",
    "jquery": "^3.4.1",
    "moment": "^2.24.0",
    "mongoose": "^5.5.15",
    "mongoose-unique-validator": "^2.0.3",
    "path": "^0.12.7",
    "rxjs": "~6.3.3",
    "tslib": "^1.9.0",
    "zone.js": "~0.8.26",
    "@angular/cdk": "^6.2.0"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "~0.13.0",
    "@angular/cli": "~7.3.3",
    "@angular/compiler-cli": "~7.2.0",
    "@angular/language-service": "~7.2.0",
    "@types/node": "~8.9.4",
    "@types/jasmine": "~2.8.8",
    "@types/jasminewd2": "~2.0.3",
    "codelyzer": "~4.5.0",
    "jasmine-core": "~2.99.1",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "~4.0.0",
    "karma-chrome-launcher": "~2.2.0",
    "karma-coverage-istanbul-reporter": "~2.0.1",
    "karma-jasmine": "~1.1.2",
    "karma-jasmine-html-reporter": "^0.2.2",
    "protractor": "~5.4.0",
    "ts-node": "~7.0.0",
    "tslint": "~5.11.0",
    "typescript": "~3.2.2"
  },
  "description": "This project was generated with [Angular CLI](https://github.com/angular/angular-cli) version 7.3.3.",
  "main": "index.js",
  "keywords": [],
  "author": "",
  "license": "ISC"
}

Если вам нужно больше код / ​​вопросы LMK.

угловая / локальная версия проекта

     _                      _                 ____ _     ___
    / \   _ __   __ _ _   _| | __ _ _ __     / ___| |   |_ _|
   / △ \ | '_ \ / _` | | | | |/ _` | '__|   | |   | |    | |
  / ___ \| | | | (_| | |_| | | (_| | |      | |___| |___ | |
 /_/   \_\_| |_|\__, |\__,_|_|\__,_|_|       \____|_____|___|
                |___/


Angular CLI: 7.3.4
Node: 10.16.0
OS: darwin x64
Angular: 7.2.15
... animations, common, compiler, compiler-cli, core, forms
... language-service, platform-browser, platform-browser-dynamic
... router

Package                           Version
-----------------------------------------------------------
@angular-devkit/architect         0.13.9
@angular-devkit/build-angular     0.13.9
@angular-devkit/build-optimizer   0.13.9
@angular-devkit/build-webpack     0.13.9
@angular-devkit/core              7.3.9
@angular-devkit/schematics        7.3.4
@angular/cdk                      6.4.7
@angular/cli                      7.3.4
@angular/material                 6.2.1
@ngtools/webpack                  7.3.9
@schematics/angular               7.3.4
@schematics/update                0.13.4
rxjs                              6.3.3
typescript                        3.2.4
webpack                           4.29.0

Страница ошибки Ошибка сетевой страницы

Ответы [ 2 ]

0 голосов
/ 09 июля 2019

Я просмотрел старые посты и наконец понял это благодаря @Dave E. Его ответ объясняет все

0 голосов
/ 24 июня 2019

Один Если ваше приложение Node JS : -

Из вашего кода server.js Похоже, у вас есть приложение Node JS.Не угловое приложение.Я не вижу здесь никакого компонента.Просто нажмите F5 и посмотрите, что произойдет?

После нажатия F5 откройте chrome и введите http://localhost:8000.. Он должен вызвать ваш метод get из вашего server.js.

Two Если ваше приложениеis " Angular ": -

Можете ли вы добавить Отладчик для Chrome как расширение в коде Visual Studio?

После добавления вы можете открытьприложение в Chrome, нажав F5.

Когда нажмете F5, он попросит вас выбрать Chrome, и он создаст файл launch.js в вашем проекте.Затем добавьте URL-адрес веб-сайта в конфигурацию.

Ниже приведен пример.

launch.json

{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "type": "chrome",
            "request": "launch",
            "name": "Launch Chrome against localhost",
            "url": "http://localhost:8000",
            "webRoot": "${workspaceFolder}"
        }
    ]
}

Попробуйте это.Надеюсь, это должно работать в вашем сценарии.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...